source: src-qt4/pc-softwaremanager/pbiBackend.cpp @ e543bca

releng/10.0.1releng/10.0.2releng/10.0.3releng/10.1
Last change on this file since e543bca was e543bca, checked in by Ken Moore <ken@…>, 10 months ago

Add the ability for the AppCafe? to install random PBI files on the system through a menu option, and update the Installed tab interface a bit to make it more uniform between the two pages. Still have a couple things to do to finish it up, but it is perfectly functional.

  • Property mode set to 100644
File size: 59.0 KB
Line 
1/***************************************************************************
2 *   Copyright (C) 2011 - iXsystems                                       *
3 *   kris@pcbsd.org  *
4 *   tim@pcbsd.org   *
5 *   ken@pcbsd.org   *
6 *                                                                         *
7 *   Permission is hereby granted, free of charge, to any person obtaining *
8 *   a copy of this software and associated documentation files (the       *
9 *   "Software"), to deal in the Software without restriction, including   *
10 *   without limitation the rights to use, copy, modify, merge, publish,   *
11 *   distribute, sublicense, and/or sell copies of the Software, and to    *
12 *   permit persons to whom the Software is furnished to do so, subject to *
13 *   the following conditions:                                             *
14 *                                                                         *
15 *   The above copyright notice and this permission notice shall be        *
16 *   included in all copies or substantial portions of the Software.       *
17 *                                                                         *
18 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       *
19 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *
20 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
21 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR     *
22 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
23 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
24 *   OTHER DEALINGS IN THE SOFTWARE.                                       *
25 ***************************************************************************/
26 //ID FORMATS: [<name> = Extras::nameToID(formalName)]
27 //  pbiID: <name>-<version>-<arch> (of locally installed PBI)
28 //  catID: <name> (of category in repo)
29 //  appID: <name> (of app in repo)
30 
31 #include <unistd.h>
32 #include "pbiBackend.h"
33
34 
35 PBIBackend::PBIBackend(QWidget *parent) : QObject(){
36   parentWidget = parent;
37   //initialize the background processes
38   PMAN = new ProcessManager();
39   connect(PMAN, SIGNAL(ProcessFinished(int)),this,SLOT(slotProcessFinished(int)) );
40   connect(PMAN, SIGNAL(ProcessMessage(int, QString)),this,SLOT(slotProcessMessage(int, QString)) );
41   connect(PMAN, SIGNAL(ProcessError(int,QStringList)),this,SLOT(slotProcessError(int,QStringList)) );
42   PENDINGREMOVAL.clear(); PENDINGDL.clear(); PENDINGINSTALL.clear(); PENDINGUPDATE.clear(); PENDINGOTHER.clear();
43   sDownload=FALSE; sInstall=FALSE; sUpdate=FALSE; sRemove=FALSE;
44   //setup the base paths
45   baseDBDir = "/var/db/pbi/";
46   sysDB = new PBIDBAccess();
47   noRepo=FALSE;
48   wardenMode=FALSE;
49   //Default User Preferences
50   settingsFile = QDir::homePath()+"/.appcafeprefs";
51   baseDlDir = QDir::homePath()+"/Downloads/";
52   if(!QFile::exists(baseDlDir)){ baseDlDir = QDir::homePath()+"/"; }
53   keepDownloads = FALSE;
54   autoXDG.clear(); autoXDG << "desktop" << "menu" << "mime" << "paths";
55   currentRepoNum = "001"; //first repo by default
56   //Filesystem watcher
57   watcher = new QFileSystemWatcher();
58   connect(watcher,SIGNAL(directoryChanged(QString)),this,SLOT(slotSyncToDatabase()) );
59   
60 }
61 
62 // ==============================
63 // ====== PUBLIC FUNCTIONS ======
64 // ==============================
65 void PBIBackend::setWardenMode(QString dir, QString ip){
66   wardenDir = dir; wardenIP = ip;
67   //wardenDir: used for direct access to a directory in the jail
68   //wardenIP: used to chroot into the jail to run commands
69   if( wardenDir.isEmpty() || wardenIP.isEmpty() ){ wardenMode = FALSE; }
70   else{ 
71     if(!wardenDir.endsWith("/")){wardenDir.append("/"); } //make sure it has a / on the end
72     wardenMode = TRUE; 
73   }
74 }
75 
76 bool PBIBackend::start(){
77   sysArch = Extras::getSystemArch(); //get the architecture for the current system
78   //Setup the base paths for the system database and downloads
79   if(wardenMode){ 
80     DBDir = wardenDir + baseDBDir;
81   }else{ 
82     DBDir = baseDBDir;
83   }
84   if(!DBDir.endsWith("/")){ DBDir.append("/"); }
85   if( !loadSettings() ){
86     saveSettings();       
87   }
88   updateDlDirPath(baseDlDir);
89   //Now setup the database access class
90   sysDB->setDBPath(DBDir);
91   sysDB->setRootCMDPrefix( addRootCMD("",TRUE).remove("\"") );
92     //Make sure the deisred repo is valid
93     QStringList repos = sysDB->availableRepos();
94     if(repos.length() > 0){ 
95       if(!repos.contains(currentRepoNum)){currentRepoNum = repos[0];} //make sure the desired repo actually exists
96     }else{
97       qDebug() << "No PBI Repositories available: disabling the browser";
98       emit NoRepoAvailable();
99       noRepo = TRUE;
100     }
101   //Set the repo
102   if(!noRepo){ sysDB->setRepo(currentRepoNum); }
103   //Now start the filesystem watcher
104   startFileSystemWatcher();
105   //Now initialize the hash lists with the database info
106   QTimer::singleShot(1,this,SLOT(slotSyncToDatabase()) );
107
108   return TRUE;
109 }
110
111 QStringList PBIBackend::installedList(){
112   return QStringList( PBIHASH.keys() ); 
113 }
114 
115 QStringList PBIBackend::browserCategories(){
116   return QStringList( CATHASH.keys() ); 
117 }
118 
119QStringList PBIBackend::browserApps( QString catID ){
120  QStringList output;
121  if(!CATHASH.contains(catID)){ return output; }
122  QStringList apps = APPHASH.keys();
123  for(int i=0; i<apps.length(); i++){
124    if(Extras::nameToID(APPHASH[apps[i]].category)==catID){ output << apps[i]; }
125  }
126  return output;
127}
128
129QStringList PBIBackend::getRecentApps(){
130  //List all new/updated applications in the last 10 days (sorted by oldest first)
131  QStringList output;
132  //Generate a string for today's date
133  QDate date = QDate::currentDate();
134  date = date.addDays(-10);
135  QString chk = date.toString("yyyyMMdd");
136  //Now compare the latest apps to this date
137  QStringList apps = APPHASH.keys();
138  QStringList  unsorted;
139  for(int i=0; i<apps.length(); i++){
140    if(Extras::newerDateTime(APPHASH[apps[i]].latestDatetime, chk)){
141      unsorted << APPHASH[apps[i]].latestDatetime + "::"+apps[i];           
142    }
143  }
144  //Now sort them by datetime and then remove the datetime stamp
145  unsorted.sort(); //oldest->newest
146  for(int i=(unsorted.length()-1); i>=0; i--){ //go in reverse order
147    output << unsorted[i].section("::",1,50);
148  }
149  return output; //newest->oldest
150}
151
152bool PBIBackend::safeToQuit(){
153  //returns true if there is no pending/current processes
154  bool ok = ( PENDINGDL.isEmpty() && PENDINGUPDATE.isEmpty() && PENDINGREMOVAL.isEmpty() \
155            && PENDINGINSTALL.isEmpty() && PENDINGOTHER.isEmpty() && cDownload.isEmpty() \
156            && cUpdate.isEmpty() && cRemove.isEmpty() && cInstall.isEmpty() && cOther.isEmpty() );
157  return ok;
158}
159// ===== Local/Repo Interaction Functions =====
160QString PBIBackend::isInstalled(QString appID){
161  //check if the pbiID was given (quick)
162  if(PBIHASH.contains(appID)){
163    if(PBIHASH[appID].path.isEmpty()){ return ""; }
164    else{ return appID; }
165  }
166  //Returns pbiID of the installed application
167  QString output;
168  if(!APPHASH.contains(appID)){
169    qDebug() << "Invalid application ID:" << appID;
170    return output;
171  }
172  QStringList pbiID = PBIHASH.keys(); //get list of installed PBI's
173  for(int i=0; i<pbiID.length();i++){
174    QString pbi = Extras::nameToID(PBIHASH[pbiID[i]].metaID);
175    if( (pbi == appID) && !PBIHASH[pbiID[i]].path.isEmpty() ){
176      output = pbiID[i];
177      break;
178    }
179  }
180  return output;
181}
182
183QString PBIBackend::upgradeAvailable(QString pbiID){
184  QString output;
185  if(!PBIHASH.contains(pbiID)){return output;}
186  QString appID = Extras::nameToID(PBIHASH[pbiID].metaID);
187  if(APPHASH.contains(appID)){
188    if(APPHASH[appID].latestVersion != PBIHASH[pbiID].version){output = APPHASH[appID].latestVersion;} 
189  }
190  return output;
191}
192
193// === PBI Actions ===
194void PBIBackend::cancelActions(QStringList pbiID){
195  qDebug() << "Cancel Actions requested for:" << pbiID;
196  for(int i=0; i<pbiID.length(); i++){
197    if(PBIHASH.contains(pbiID[i]) ){
198      //Remove any pending actions for this pbiID
199      PENDINGDL = removePbiCMD(pbiID[i],PENDINGDL);
200      PENDINGINSTALL = removePbiCMD(pbiID[i],PENDINGINSTALL);
201      PENDINGREMOVAL = removePbiCMD(pbiID[i],PENDINGREMOVAL);
202      PENDINGUPDATE = removePbiCMD(pbiID[i],PENDINGUPDATE);
203      PENDINGOTHER = removePbiCMD(pbiID[i],PENDINGOTHER); //doubtful that there will even be anything here
204      //Now cancel any current operations for this pbiID
205      if(cDownload==pbiID[i]){ sDownload=TRUE; PMAN->stopProcess(ProcessManager::DOWNLOAD); }
206      if(cUpdate==pbiID[i]){ 
207              if( lUpdate.startsWith("DLSTAT::") || lUpdate.startsWith("DLSTART") ){
208                //In download phase of the update - just kill it
209                PMAN->stopProcess(ProcessManager::UPDATE); 
210              }else{
211                //In the install phase of the update
212                sUpdate=TRUE; //need to clean up after it finishes
213              }
214      }
215      if(cRemove==pbiID[i]){ sRemove=TRUE; }
216      if(cInstall==pbiID[i]){ sInstall=TRUE; }
217      //Ignore OTHER process - those commands are pretty much instant
218    }
219  }
220  //Now refresh the PBIHASH info (remove stale entries, update statuses, etc..)
221  slotSyncToDatabase(TRUE);
222}
223
224void PBIBackend::upgradePBI(QStringList pbiID){
225  qDebug() << "PBI Upgrades requested for:" << pbiID;
226  for(int i=0; i<pbiID.length(); i++){
227    if( PBIHASH.contains(pbiID[i]) ){
228      if( PBIHASH[pbiID[i]].status == InstalledPBI::UPDATEAVAILABLE ){
229        QString cmd = generateUpdateCMD(pbiID[i]);
230        PENDINGUPDATE << pbiID[i] + ":::" + cmd;
231        PBIHASH[pbiID[i]].setStatus(InstalledPBI::PENDINGUPDATE);
232        emit PBIStatusChange(pbiID[i]);
233      }else{
234        qDebug() << "No update available for:" << pbiID[i];     
235      }
236    }else{
237      qDebug() << pbiID[i] << "not a valid PBI to update";         
238    }
239  }
240  //Now check/start the update process
241  QTimer::singleShot(0,this,SLOT(checkProcesses()) );
242}
243
244void PBIBackend::removePBI(QStringList pbiID){
245  qDebug() << "PBI Removals requested for:" << pbiID;
246  QStringList xdgrem; xdgrem << "remove-desktop" << "remove-menu" << "remove-mime" << "remove-paths";
247  for(int i=0; i<pbiID.length(); i++){
248    if(PBIHASH.contains(pbiID[i])){
249      //Remove XDG entries for this app
250      PENDINGREMOVAL << pbiID[i]+":::"+generateXDGCMD(pbiID[i],xdgrem, FALSE);
251      //Remove the app itself
252      PENDINGREMOVAL << pbiID[i]+":::"+generateRemoveCMD(pbiID[i]);
253      //Now update the status
254      PBIHASH[pbiID[i]].setStatus(InstalledPBI::PENDINGREMOVAL);
255      emit PBIStatusChange(pbiID[i]);
256    }else{
257      qDebug() << pbiID[i] << "not a valid PBI to remove";         
258    }
259  }
260  //Now check/start the remove process
261  QTimer::singleShot(0,this,SLOT(checkProcesses()) );
262}
263
264void PBIBackend::installApp(QStringList appID){
265  qDebug() << "Install App requested for:" << appID;
266  for(int i=0; i<appID.length(); i++){
267    if(!APPHASH.contains(appID[i])){ 
268      qDebug() << appID[i] << "is not a valid application";
269      continue; //go to the next item is this one is invalid
270    } 
271    //Find out if app is installed already
272    QString pbiID = isInstalled(appID[i]);
273    if(pbiID.isEmpty()){
274      //Not installed at the moment, queue up the installation
275      qDebug() << "Fresh install of appID:" << appID[i];
276      queueInstall(appID[i]);
277    }else{
278      //It is already registered as installed
279      if( APPHASH[appID[i]].latestVersion == PBIHASH[pbiID].version ){
280        //latest version already installed, revert to backup version
281        qDebug() << "Revert install of appID:" << appID[i];
282        queueInstall(appID[i], APPHASH[appID[i]].backupVersion);
283      }else{
284        //older version installed - try to update the app
285        qDebug() << "Update install of appID:" << appID[i];
286        upgradePBI(QStringList() << pbiID);
287      }
288    }
289  } // end of loop over items
290  //Now check/start the remove process
291  QTimer::singleShot(0,this,SLOT(checkProcesses()) );
292  //Now emit the signal that items have changed or been added
293  emit LocalPBIChanges();
294}
295
296void PBIBackend::installPBIFromFile(QStringList files){
297  qDebug() << "Install PBI files requested for:" << files;
298  for(int i=0; i<files.length(); i++){
299    if(!files[i].endsWith(".pbi")){ continue; } //invalid file
300    //Now load the info about this PBI
301    bool root = PBIFileNeedsRoot(files[i]);
302    //Now create the commands
303    QString cmd = addRootCMD("pc-pbigui "+files[i], root);
304    //Don't bother integrating it furthur, the pc-pbigui will handle it all better
305    //  and if it actually gets installed it will automatically get detected/added to the AppCafe list
306    PENDINGOTHER << "EXTERNAL:::"+cmd;
307  }
308  QTimer::singleShot(0,this,SLOT(checkProcesses()) );
309}
310
311void PBIBackend::addDesktopIcons(QStringList pbiID, bool allusers){ // add XDG desktop icons
312  for(int i=0; i<pbiID.length(); i++){
313    if(PBIHASH.contains(pbiID[i])){
314      //generate the command
315      QString cmd = generateXDGCMD(pbiID[i],QStringList()<<"desktop",allusers);
316      //Now add it to the queue
317      PENDINGOTHER << pbiID[i]+":::"+cmd;
318    }
319  }
320  //Now check/start the process
321  QTimer::singleShot(0,this,SLOT(checkProcesses()) );
322}
323
324void PBIBackend::addMenuIcons(QStringList pbiID, bool allusers){ // add XDG menu icons
325  for(int i=0; i<pbiID.length(); i++){
326    if(PBIHASH.contains(pbiID[i])){
327      //generate the command
328      QString cmd = generateXDGCMD(pbiID[i],QStringList()<<"menu",allusers);
329      //Now add it to the queue
330      PENDINGOTHER << pbiID[i]+":::"+cmd;
331    }
332  }
333  //Now check/start the process
334  QTimer::singleShot(0,this,SLOT(checkProcesses()) );
335}
336
337void PBIBackend::addPaths(QStringList pbiID, bool allusers){ // create path links
338  for(int i=0; i<pbiID.length(); i++){
339    if(PBIHASH.contains(pbiID[i])){
340      //generate the command
341      QString cmd = generateXDGCMD(pbiID[i],QStringList()<<"paths",allusers);
342      //Now add it to the queue
343      PENDINGOTHER << pbiID[i]+":::"+cmd;
344    }
345  }
346  //Now check/start the process
347  QTimer::singleShot(0,this,SLOT(checkProcesses()) );   
348}
349
350void PBIBackend::addMimeTypes(QStringList pbiID, bool allusers){ // remove path links
351  for(int i=0; i<pbiID.length(); i++){
352    if(PBIHASH.contains(pbiID[i])){
353      //generate the command
354      QString cmd = generateXDGCMD(pbiID[i],QStringList()<<"mime",allusers);
355      //Now add it to the queue
356      PENDINGOTHER << pbiID[i]+":::"+cmd;
357    }
358  }
359  //Now check/start the process
360  QTimer::singleShot(0,this,SLOT(checkProcesses()) );   
361}
362
363void PBIBackend::rmDesktopIcons(QStringList pbiID, bool allusers){ // remove XDG desktop icons
364  for(int i=0; i<pbiID.length(); i++){
365    if(PBIHASH.contains(pbiID[i])){
366      //generate the command
367      QString cmd = generateXDGCMD(pbiID[i],QStringList()<<"remove-desktop",allusers);
368      //Now add it to the queue
369      PENDINGOTHER << pbiID[i]+":::"+cmd;
370    }
371  }
372  //Now check/start the process
373  QTimer::singleShot(0,this,SLOT(checkProcesses()) );   
374}
375
376void PBIBackend::rmMenuIcons(QStringList pbiID, bool allusers){ // remove XDG menu icons
377  for(int i=0; i<pbiID.length(); i++){
378    if(PBIHASH.contains(pbiID[i])){
379      //generate the command
380      QString cmd = generateXDGCMD(pbiID[i],QStringList()<<"remove-menu",allusers);
381      //Now add it to the queue
382      PENDINGOTHER << pbiID[i]+":::"+cmd;
383    }
384  }
385  //Now check/start the process
386  QTimer::singleShot(0,this,SLOT(checkProcesses()) );   
387}
388
389void PBIBackend::rmPaths(QStringList pbiID, bool allusers){ // remove path links
390  for(int i=0; i<pbiID.length(); i++){
391    if(PBIHASH.contains(pbiID[i])){
392      //generate the command
393      QString cmd = generateXDGCMD(pbiID[i],QStringList()<<"remove-paths",allusers);
394      //Now add it to the queue
395      PENDINGOTHER << pbiID[i]+":::"+cmd;
396    }
397  }
398  //Now check/start the process
399  QTimer::singleShot(0,this,SLOT(checkProcesses()) );   
400}
401
402void PBIBackend::rmMimeTypes(QStringList pbiID, bool allusers){ // remove path links
403  for(int i=0; i<pbiID.length(); i++){
404    if(PBIHASH.contains(pbiID[i])){
405      //generate the command
406      QString cmd = generateXDGCMD(pbiID[i],QStringList()<<"remove-mime",allusers);
407      //Now add it to the queue
408      PENDINGOTHER << pbiID[i]+":::"+cmd;
409    }
410  }
411  //Now check/start the process
412  QTimer::singleShot(0,this,SLOT(checkProcesses()) );   
413}
414
415void PBIBackend::enableAutoUpdate(QString pbiID, bool enable){
416  if(!PBIHASH.contains(pbiID)){return;}
417  //Generate the command
418  QString cmd = generateAutoUpdateCMD(pbiID,enable);
419  //Now put it in the queue
420  PENDINGOTHER << pbiID+":::"+cmd;
421  //Now check/start the process
422  QTimer::singleShot(0,this,SLOT(checkProcesses()) );
423}
424
425 // === Information Retrieval functions ===
426QStringList PBIBackend::PBIInfo( QString pbiID, QStringList infoList){
427  QStringList output;
428  if(!PBIHASH.contains(pbiID)){ return output; }
429  for(int i=0; i<infoList.length(); i++){
430    if(infoList[i]=="name"){ output << PBIHASH[pbiID].name; }
431    else if(infoList[i]=="version"){ output << PBIHASH[pbiID].version; }
432    else if(infoList[i]=="author"){ output << PBIHASH[pbiID].author; }
433    else if(infoList[i]=="website"){ output << PBIHASH[pbiID].website; }
434    else if(infoList[i]=="arch"){ output << PBIHASH[pbiID].arch; }
435    else if(infoList[i]=="path"){ output << PBIHASH[pbiID].path; }
436    else if(infoList[i]=="icon"){ 
437        QString icon = PBIHASH[pbiID].icon;
438        if( QFile::exists(icon) ){ output << icon; }
439        else{ output << ""; }
440    }else if(infoList[i]=="license"){ output << PBIHASH[pbiID].license; }
441    else if(infoList[i]=="metaid"){ output << PBIHASH[pbiID].metaID; }
442    else if(infoList[i]=="status"){ output << currentAppStatus(pbiID); }
443    else if(infoList[i]=="maintainer"){ output << PBIHASH[pbiID].maintainer; }
444    else if(infoList[i]=="description"){ output << PBIHASH[pbiID].description; }
445    else if(infoList[i]=="date"){ output << PBIHASH[pbiID].mdate; }
446    else if(infoList[i]=="fbsdversion"){ output << PBIHASH[pbiID].fbsdversion; }
447    //Now the boolians
448    else if(infoList[i]=="requiresroot"){ 
449      if(PBIHASH[pbiID].rootInstall){output<<"true";}
450      else{ output<<"false";}
451    }
452    else if(infoList[i]=="autoupdate"){ 
453      if(PBIHASH[pbiID].autoUpdate){output<<"true";}
454      else{ output<<"false";}
455    }
456    else if(infoList[i]=="hasdesktopicons"){ 
457      if(PBIHASH[pbiID].desktopIcons){output<<"true";}
458      else{ output<<"false";}
459    }
460    else if(infoList[i]=="hasmenuicons"){ 
461      if(PBIHASH[pbiID].menuIcons){output<<"true";}
462      else{ output<<"false";}
463    }
464    else{ output << ""; }
465  }
466  //qDebug()<< "Info Requested for:" << pbiID << infoList << "Info:" << output;
467  return output;
468}       
469
470QStringList PBIBackend::CatInfo( QString catID, QStringList infoList){
471  QStringList output;
472  if(!CATHASH.contains(catID)){ return output; }
473  for(int i=0; i<infoList.length(); i++){
474    if(infoList[i]=="name"){ output << CATHASH[catID].name; }
475    else if(infoList[i]=="icon"){ output << CATHASH[catID].localIcon; }
476    else if(infoList[i]=="description"){ output << CATHASH[catID].description; }   
477    else{ output << ""; }
478  }
479  //qDebug()<< "Info Requested for:" << catID << infoList << "Info:" << output;
480  return output;
481}
482
483QStringList PBIBackend::AppInfo( QString appID, QStringList infoList){
484  QStringList output;
485  if(!APPHASH.contains(appID)){ return output; }
486  for(int i=0; i<infoList.length(); i++){
487    if(infoList[i]=="name"){ output << APPHASH[appID].name; }
488    else if(infoList[i]=="author"){ output << APPHASH[appID].author; }
489    else if(infoList[i]=="website"){ output << APPHASH[appID].website; }
490    else if(infoList[i]=="icon"){ output << APPHASH[appID].localIcon; }
491    else if(infoList[i]=="license"){ output << APPHASH[appID].license; }
492    else if(infoList[i]=="type"){ output << APPHASH[appID].appType; }
493    else if(infoList[i]=="description"){ output << APPHASH[appID].description; }
494    else if(infoList[i]=="shortdescription"){ output << APPHASH[appID].shortdescription; }
495    else if(infoList[i]=="maintainer"){ output << APPHASH[appID].maintainer; }
496    else if(infoList[i]=="category"){ output << APPHASH[appID].category; }
497    else if(infoList[i]=="latestversion"){ output << APPHASH[appID].latestVersion; }
498    else if(infoList[i]=="latestarch"){ output << APPHASH[appID].latestArch; }
499    else if(infoList[i]=="latestsize"){ output << APPHASH[appID].latestSizeK; }
500    else if(infoList[i]=="backupversion"){ output << APPHASH[appID].backupVersion; }
501    else if(infoList[i]=="backuparch"){ output << APPHASH[appID].backupArch; }
502    else if(infoList[i]=="backupsize"){ output << APPHASH[appID].backupSizeK; }
503    //Now the boolians
504    else if(infoList[i]=="requiresroot"){ 
505      if(APPHASH[appID].requiresroot){output<<"true";}
506      else{ output<<"false";}
507    }
508    else{ output << ""; }
509  }
510  //qDebug()<< "Info Requested for:" << appID << infoList << "Info:" << output;
511  return output;
512}
513
514QString PBIBackend::currentAppStatus( QString appID, bool rawstatus ){
515  QString output;
516  int status = -999;
517  QString metaID;
518  //pbiID given (quicker)
519  if(PBIHASH.contains(appID)){ status = PBIHASH[appID].status; metaID = PBIHASH[appID].metaID; }
520  else{
521    //appID given
522    if(!APPHASH.contains(appID)){ return ""; }
523    QStringList pbilist = PBIHASH.keys();
524    for(int i=0; i<pbilist.length(); i++){
525      if(PBIHASH[pbilist[i]].metaID == appID){ status = PBIHASH[pbilist[i]].status; metaID=appID; break; }
526    }
527  }
528  //Determine if the app is currently in a pending/running state
529  if(rawstatus){ //output the raw status for active processes
530    switch (status){
531        case InstalledPBI::DOWNLOADING:
532          output = lDownload; break;
533        case InstalledPBI::INSTALLING:
534          output = lInstall; break;
535        case InstalledPBI::REMOVING:
536          output = lRemove; break;
537        case InstalledPBI::UPDATING:
538          output = lUpdate; break;
539        default:
540          output.clear();
541    }
542  }else{
543    switch (status){
544        case InstalledPBI::DOWNLOADING:
545          if(sDownload){ output = tr("Download Canceled"); }
546          if(lDownload.startsWith("DLSTAT::")){
547            QString percent = lDownload.section("::",1,1);
548            output = QString(tr("Downloading: %1%")).arg( percent );
549          }else if(lDownload == "DLDONE"){
550            output = tr("Download Finished");
551          }else{
552            output = tr("Download Starting"); 
553          }
554          break;
555        case InstalledPBI::INSTALLING:
556          if(sInstall){ output = tr("Install Canceled (will remove)"); }
557          else{ output = tr("Installing"); }
558          break;
559        case InstalledPBI::REMOVING:
560          if(sRemove){ output = tr("Removal Canceled (will reinstall)"); }
561          else{ output = tr("Removing Application"); }
562          break;
563        case InstalledPBI::UPDATING:
564          if(sUpdate){ output = tr("Update's cannot be canceled"); }
565          else if(lUpdate.startsWith("DLSTAT::")){
566            QString percent = lUpdate.section("::",1,1);
567            output = QString(tr("Update Downloading: %1%")).arg( percent );
568          }else if(lUpdate == "DLDONE"){
569            output = tr("Starting Update");
570          }else if(lUpdate == "DLSTART"){
571            output = tr("Starting Download");
572          }else{
573            output = tr("Updating");
574          }
575          break;
576        case InstalledPBI::PENDINGDOWNLOAD:
577          output = tr("Pending Download"); break;
578        case InstalledPBI::PENDINGINSTALL:
579          output = tr("Pending Install"); break;
580        case InstalledPBI::PENDINGREMOVAL:
581          output = tr("Pending Removal"); break;
582        case InstalledPBI::PENDINGUPDATE:
583          output = tr("Pending Update"); break;
584        case InstalledPBI::UPDATEAVAILABLE:
585          output = QString(tr("Update Available: %1")).arg(APPHASH[metaID].latestVersion);
586          break;
587        default: //do nothing for the rest
588          output.clear();
589    }
590  }
591  return output;
592}
593
594bool PBIBackend::isWorking(QString pbiID){
595  if( !PBIHASH.contains(pbiID) ){ return FALSE; }
596
597  bool notworking = (PBIHASH[pbiID].status == InstalledPBI::UPDATEAVAILABLE || PBIHASH[pbiID].status == InstalledPBI::NONE );
598  return !notworking;
599}
600
601QStringList PBIBackend::pbiBinList(QString pbiID){
602  QStringList output;
603  //qDebug() << "Start Search for Binaries:" << pbiID;
604  if( !PBIHASH.contains(pbiID) ){ return output; }
605  //Now prod the database to see what binaries are currently available to run
606  QDir bDir(PBIHASH[pbiID].path+"/.xdg-menu/"); 
607  if(bDir.exists()){
608    QStringList bList = bDir.entryList(QStringList() << "*.desktop");
609    for(int i =0; i<bList.length(); i++){
610      QStringList contents = Extras::readFile(bDir.absoluteFilePath(bList[i]));
611        //qDebug() << " - Check file:" << bList[i] << contents;
612      //Make sure that it is a visible entry
613      if(!contents.contains("NoDisplay=true")){
614        //qDebug() << " -- visible entry";
615        QString name;
616        //Get the locale code
617        QString loc = QLocale::system().name();
618        bool lName=false;
619        for(int j=0; j<contents.length(); j++){
620          if(contents[j].startsWith("Name=") && !lName){ name = contents[j].section("=",1,10);  }
621          else if(contents[j].startsWith("Name["+loc+"]=")){ name = contents[j].section("=",1,10);  lName=true; }
622        }
623        //Format the output string
624        if( !name.isEmpty() ){
625          output << name.simplified()+"::::"+bDir.absoluteFilePath(bList[i]);
626        }
627      }
628    } //end loop over files
629  }
630  return output;
631}
632
633// === Configuration Management ===
634void PBIBackend::openConfigurationDialog(){
635  //temporarily disable the filesystem watcher (causes issues with repo changes)
636  stopFileSystemWatcher();
637  //Now setup the UI
638  ConfigDialog *cfg = new ConfigDialog(parentWidget);
639  cfg->xdgOpts = autoXDG;
640  cfg->keepDownloads = keepDownloads;
641  cfg->downloadDir = baseDlDir;
642  cfg->DB = sysDB; //for access to database operations
643  cfg->setupDone();
644  //Now run it
645  cfg->exec(); //makes it modal and waits for it to finish
646  //Now see if there are changes to save
647  if(cfg->applyChanges){
648    autoXDG = cfg->xdgOpts;
649    keepDownloads = cfg->keepDownloads;
650    updateDlDirPath(cfg->downloadDir);
651    //Now save the configuration data to file
652    saveSettings();
653
654  }
655  //Now re-enable the filesystem watcher
656  startFileSystemWatcher();
657  //Now re-sync the repo info
658  syncCurrentRepo();
659}
660
661// === Import/Export PBI Lists ===
662bool PBIBackend::exportPbiListToFile(QString filepath){
663  bool ok = FALSE;
664  //get the currently installed PBI's
665  QStringList list = PBIHASH.keys();
666  QStringList installed;
667  for(int i=0; i<list.length(); i++){
668    if(!PBIHASH[list[i]].path.isEmpty()){ installed << PBIHASH[list[i]].metaID; }         
669  }
670  qDebug() << "Export List:" << installed;
671  //Now save the list
672  if(installed.isEmpty()){ ok = TRUE; }
673  else{ ok = Extras::writeFile(filepath,installed); }
674  return ok;
675}
676
677bool PBIBackend::importPbiListFromFile(QString filepath){
678  bool ok = FALSE;
679  if(!QFile::exists(filepath)){ return ok; }
680  QStringList inlist = Extras::readFile(filepath);
681  if(inlist.isEmpty()){ return ok; }
682  qDebug() << "Import List:" << inlist;
683  //Now sort the apps based on validity
684  QStringList good, bad, current; 
685  for(int i=0; i<inlist.length(); i++){
686    QString app = inlist[i].toLower();
687    if(app.isEmpty()){continue;}
688    else if(!APPHASH.contains(app)){ bad << inlist[i]; }
689    else if( !isInstalled(app).isEmpty() ){ current << inlist[i]; }
690    else{ good << app; } //make sure to use the appID here
691  }
692  ok = TRUE;
693  //List the results
694  if(good.isEmpty()){
695    QString results = tr("No applications to install from this list.")+"\n"+tr("Results:")+"\n";
696    if(!bad.isEmpty()){ results.append( QString(tr("Unavailable Apps: %1")).arg(bad.join(",  "))+"\n" ); }
697    if(!current.isEmpty()){ results.append( QString(tr("Currently Installed: %1")).arg(current.join(",  "))+"\n" ); }
698    QMessageBox::information(0,tr("Import Results"),results);
699  }else{
700    QString results = tr("Are you sure you wish to install these applications?")+"\n\n"+good.join(", ");
701    if( QMessageBox::question(0,tr("Import Results"),results,QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes){
702      //Go ahead and install these applications
703      installApp(good);
704    }
705  }
706  return ok;
707}
708
709 // ==========================
710 // ====== PUBLIC SLOTS ======
711 // ==========================
712 // NOTE: These functions should only be called from a QTimer::singleShot()
713 //    Because outputs come via different signals (due to time for these functions to run)
714 
715void PBIBackend::startAppSearch(){
716 //  Outputs come via the "SearchComplete(QStringList best,QStringList rest)" signal
717 QString search = searchTerm; //This public variable needs to be set beforehand by the calling process
718 QStringList best, rest;
719 //Now perform the search and categorize it
720 search = search.toLower();
721 QStringList namematch, tagmatch, descmatch;
722 QStringList app = APPHASH.keys();
723 for(int i=0; i<app.length(); i++){
724   if(APPHASH[app[i]].name.toLower() == search){ best << app[i]; } //exact match - top of the "best" list
725   else if(APPHASH[app[i]].name.toLower().contains(search)){ namematch << app[i]; }
726   else if(APPHASH[app[i]].tags.contains(search)){ tagmatch << app[i]; }
727   else if(APPHASH[app[i]].description.contains(search)){ descmatch << app[i]; }
728 }
729 //Now sort the lists and assign a priority
730 namematch.sort(); tagmatch.sort(); descmatch.sort();
731 best << namematch;
732 if(best.isEmpty()){ best << tagmatch; }
733 else{ rest << tagmatch; }
734 if(best.isEmpty()){ best << descmatch; }
735 else{ rest << descmatch; }
736
737 //Now emit the signal with the results
738 emit SearchComplete(best,rest);
739}
740
741void PBIBackend::startSimilarSearch(){
742  //  Outputs come via the "SimilarFound(QStringList results)" signal
743  QString sID = searchSimilar; // this public variable needs to be set beforehand by the calling process
744  QStringList output; 
745  if(!APPHASH.contains(sID)){ return; } 
746  //Now find the tags on the given ID
747  QStringList stags = APPHASH[sID].tags;
748  QStringList apps = APPHASH.keys();
749  QStringList unsorted;
750  int maxMatch=0;
751  for(int i=0; i<apps.length(); i++){
752    if(apps[i]==sID){continue;} //skip the app we were given for search parameters
753    QStringList tags = APPHASH[apps[i]].tags;
754    int match=0;
755    for(int j=0; j<stags.length(); j++){
756       if(tags.indexOf(stags[j]) != -1){ match++; }
757    }
758    if(match > 1){ unsorted << QString::number(match)+"::"+apps[i]; }
759    if(match > maxMatch){ maxMatch = match; }
760  }
761  unsorted.sort();
762  for(int i=unsorted.length(); i>0; i--){
763    if( unsorted[i-1].section("::",0,0).toInt() > (maxMatch-1) ){
764      output << unsorted[i-1].section("::",1,50);
765    }else if( output.length() < 5 ){ //not enough matches, grab the next set too
766      output << unsorted[i-1].section("::",1,50);
767      maxMatch--;
768    }else{ break; } //already sorted and the rest are even lower match rating
769  }
770  //Now emit the signal with the results
771  emit SimilarFound(output);
772}
773
774 // ===============================
775 // ====== PRIVATE FUNCTIONS ======
776 // ===============================
777bool PBIBackend::saveSettings(){
778  //Generate the file layout
779  QStringList file;
780  file << "POSTINSTALL="+autoXDG.join(",").simplified();
781  file << "REPONUMBER="+sysDB->currentRepo();
782  if(keepDownloads){ file << "KEEPDOWNLOADS=TRUE"; }
783  else{ file << "KEEPDOWNLOADS=FALSE"; }
784  file << "DOWNLOADDIR="+baseDlDir;
785  //Now save the file
786  bool ok = Extras::writeFile(settingsFile, file);
787  return ok;
788}
789
790bool PBIBackend::loadSettings(){
791  if(!QFile::exists(settingsFile)){ return FALSE; }
792  QStringList file = Extras::readFile(settingsFile);
793  if(file.isEmpty()){ return FALSE; }
794  for(int i=0; i<file.length(); i++){
795    if(file[i].startsWith("POSTINSTALL=")){ autoXDG = file[i].section("=",1,1).split(","); }
796    else if(file[i].startsWith("REPONUMBER=")){ sysDB->setRepo(file[i].section("=",1,1)); }
797    else if(file[i].startsWith("KEEPDOWNLOADS=")){ 
798      if(file[i].section("=",1,1) == "TRUE"){ keepDownloads = TRUE; }
799      else{ keepDownloads = FALSE; }
800    }else if(file[i].startsWith("DOWNLOADDIR=")){ updateDlDirPath(file[i].section("=",1,1)); }
801  }
802  return TRUE;
803}
804 
805 QString PBIBackend::addRootCMD(QString cmd, bool needRoot){
806   //Check for warden and root permissions and adjust the command accordingly
807   if(wardenMode){
808     cmd.prepend("warden chroot "+wardenIP+" \""); cmd.append("\"");
809   }else if( needRoot ){
810     cmd.prepend("pc-su \""); cmd.append("\"");     
811   }
812   return cmd;
813 }
814 
815 QString PBIBackend::generateUpdateCMD(QString pbiID){
816   QString output;
817   if(!PBIHASH.contains(pbiID)){ return output; }
818   output = "pbi_update "+pbiID;
819   output = addRootCMD(output, PBIHASH[pbiID].rootInstall);
820   return output;
821 }
822 
823 QString PBIBackend::generateRemoveCMD(QString pbiID){
824   QString output;
825   if(!PBIHASH.contains(pbiID)){ return output; }
826   output = "pbi_delete "+pbiID;
827   output = addRootCMD(output, PBIHASH[pbiID].rootInstall);
828   return output;       
829 }
830 
831 QString PBIBackend::generateAutoUpdateCMD(QString pbiID, bool enable){
832   QString output;
833   if(!PBIHASH.contains(pbiID)){ return output; }
834   output = "pbi_update";
835   if(enable){ output.append(" --enable-auto"); }
836   else{ output.append(" --disable-auto"); }
837   output.append(" "+PBIHASH[pbiID].metaID);
838   output = addRootCMD(output, PBIHASH[pbiID].rootInstall);
839   return output;       
840 }
841
842 QString PBIBackend::generateXDGCMD(QString pbiID, QStringList actions, bool allusers){
843   QString output;
844   if(!PBIHASH.contains(pbiID)){ return output; }
845   output = "pbi_icon";
846   if(actions.contains("desktop")){ output.append(" add-desktop"); }
847   if(actions.contains("menu")){ output.append(" add-menu"); }
848   if(actions.contains("paths")){ output.append(" add-pathlnk"); }
849   if(actions.contains("mime")){ output.append(" add-mime"); }
850   if(actions.contains("remove-desktop")){ output.append(" del-desktop"); }
851   if(actions.contains("remove-menu")){ output.append(" del-menu"); }
852   if(actions.contains("remove-paths")){ output.append(" del-pathlnk"); }
853   if(actions.contains("remove-mime")){ output.append(" del-mime"); }
854   //Check command actions
855   if(output == "pbi_icon"){ 
856     output.clear(); //no actions - do nothing
857   }else{
858     output.append(" "+pbiID);
859     output = addRootCMD(output,allusers);
860   }
861   return output;       
862 }
863 
864 QString PBIBackend::generateDownloadCMD(QString appID, QString version){
865   if(!APPHASH.contains(appID)){ return ""; }
866   QString output = "pbi_add -R --repo "+sysDB->currentRepo();
867   if(!version.isEmpty()){ output.append(" --rVer "+version); }
868   output.append(" "+appID);
869   return output;
870 }
871 
872 QString PBIBackend::generateInstallCMD(QString appID, QString filename){
873   QString output = "pbi_add --licagree "+filename;
874   output = addRootCMD(output, PBIHASH[appID].rootInstall);
875   return output;
876 }
877 
878QStringList PBIBackend::removePbiCMD(QString pbiID, QStringList list){
879   //Used for removing any pending CMD's for a particular pbiID
880   QStringList output;
881   for(int i=0; i<list.length(); i++){
882     if(!list[i].startsWith(pbiID)){ output << list[i]; }         
883   }
884   return output;
885}
886
887bool PBIBackend::PBIFileNeedsRoot(QString filepath){
888  //Used to grab information from a stand-along *.pbi file
889  bool root = false;
890  QStringList info = Extras::getCmdOutput("pbi_add -i "+filepath);
891  //Only check if it needs root
892  root = !info.filter("RootInstall:").join("").contains("NO");
893  return root;
894}
895
896void PBIBackend::queueInstall(QString appID, QString version){
897  //This function assumes that the new app/version combination is not already installed on the system
898  //  and that upgrading is not an option (fresh download/install)     
899  if( !APPHASH.contains(appID) ){ return; }
900  //verify that the version is available
901  if( version.isEmpty() ){ version = APPHASH[appID].latestVersion; }
902  bool useLatest = false;
903  if( version == APPHASH[appID].latestVersion){ useLatest=true; }
904  else if( version != APPHASH[appID].backupVersion ){ return; } //invalid version
905  //Check to see if the file is already downloaded
906  QString dlFile, arch;
907  if(useLatest){ dlFile = APPHASH[appID].latestFilename; arch = APPHASH[appID].latestArch; }
908  else{ dlFile = APPHASH[appID].backupFilename; arch = APPHASH[appID].backupArch; }
909  //Generate PBI ID
910  QString newID = appID+"-"+version+"-"+arch;
911  QString oldID = isInstalled(appID); //look for existing installation of this app
912
913  //Create Commands and add them to the proper queue
914  if( QFile::exists(dlDir+dlFile) ){
915    if(!oldID.isEmpty()){
916      //Remove the old application first
917      PENDINGINSTALL << oldID+":::"+generateRemoveCMD(oldID);
918    }
919    PENDINGINSTALL << newID+":::"+generateInstallCMD(appID,dlFile);
920  }else{
921    //Generate download command
922    PENDINGDL << newID+":::"+generateDownloadCMD(appID, version);
923  }
924  //Setup the HASH entry for the new PBI
925  PBIHASH.insert(newID, InstalledPBI());
926  PBIHASH[newID].metaID = appID;
927  PBIHASH[newID].version = version;
928  PBIHASH[newID].arch = arch;
929  PBIHASH[newID].downloadfile = dlFile;
930  syncPBI(newID,FALSE);
931 
932}
933 
934 // ===============================
935 // ======   PRIVATE SLOTS   ======
936 // ===============================
937 void PBIBackend::updateDlDirPath(QString newbase){
938   baseDlDir = newbase;
939   if(wardenMode){ 
940     dlDir = wardenDir + baseDlDir;
941   }else{ 
942     dlDir = baseDlDir; 
943   }
944   if(!dlDir.endsWith("/")){ dlDir.append("/"); } 
945 }
946 
947 // Internal Process Management
948 void PBIBackend::checkProcesses(){
949   bool again=FALSE;
950   if( cDownload.isEmpty() && !PENDINGDL.isEmpty() ){
951     //internal management
952     cDownload = PENDINGDL[0].section(":::",0,0); //should be a pbiID -ONLY-
953     QString cmd = PENDINGDL[0].section(":::",1,50);
954     PENDINGDL.removeAt(0);       
955     if( !cmd.isEmpty() && PBIHASH.contains(cDownload) ){
956       //Update the PBI status
957       PBIHASH[cDownload].setStatus(InstalledPBI::DOWNLOADING);
958       emit PBIStatusChange(cDownload);
959       //Start the process
960       PMAN->goToDirectory(ProcessManager::DOWNLOAD,dlDir);
961       PMAN->startProcess(ProcessManager::DOWNLOAD,cmd);
962     }else{
963       cDownload.clear();
964       again=TRUE; //Move to the next pending download
965     }
966   }
967   if( cInstall.isEmpty() && !PENDINGINSTALL.isEmpty() ){
968     //internal management
969     cInstall = PENDINGINSTALL[0].section(":::",0,0); //should be a pbiID -ONLY-
970     QString cmd = PENDINGINSTALL[0].section(":::",1,50);
971     PENDINGINSTALL.removeAt(0);         
972     if( !cmd.isEmpty() && PBIHASH.contains(cInstall) ){
973       //Update the PBI status
974       PBIHASH[cInstall].setStatus(InstalledPBI::INSTALLING);
975       emit PBIStatusChange(cInstall);
976       //Start the process
977       PMAN->goToDirectory(ProcessManager::INSTALL,dlDir);
978       PMAN->startProcess(ProcessManager::INSTALL,cmd);
979     }else{
980       cInstall.clear();
981       again=TRUE; //Move to the next pending install
982     }
983   }
984   if( cRemove.isEmpty() && !PENDINGREMOVAL.isEmpty() ){
985     //internal management
986     cRemove = PENDINGREMOVAL[0].section(":::",0,0); //should be a pbiID -ONLY-
987     QString cmd = PENDINGREMOVAL[0].section(":::",1,50);
988     PENDINGREMOVAL.removeAt(0);         
989     if( !cmd.isEmpty() && PBIHASH.contains(cRemove) ){
990       //Update the PBI status
991       PBIHASH[cRemove].setStatus(InstalledPBI::REMOVING);
992       emit PBIStatusChange(cRemove);
993       //Start the process
994       PMAN->startProcess(ProcessManager::REMOVE,cmd);
995     }else{
996       cRemove.clear();
997       again=TRUE; //Move to the next pending removal
998     }
999   }
1000   if( cUpdate.isEmpty() && !PENDINGUPDATE.isEmpty() ){
1001     //internal management
1002     cUpdate = PENDINGUPDATE[0].section(":::",0,0); //should be a pbiID -ONLY-
1003     QString cmd = PENDINGUPDATE[0].section(":::",1,50);
1004     PENDINGUPDATE.removeAt(0);   
1005     if( !cmd.isEmpty() && PBIHASH.contains(cUpdate) ){
1006       //Update the PBI status
1007       PBIHASH[cUpdate].setStatus(InstalledPBI::UPDATING);
1008       emit PBIStatusChange(cUpdate);
1009       //Start the process
1010       PMAN->startProcess(ProcessManager::UPDATE,cmd);
1011     }else{
1012       cUpdate.clear();
1013       again=TRUE; //Move to the next pending update
1014     }
1015   }
1016   if( cOther.isEmpty() && !PENDINGOTHER.isEmpty() ){
1017     //internal management
1018     cOther = PENDINGOTHER[0].section(":::",0,0); //should be a pbiID -ONLY-
1019     QString cmd = PENDINGOTHER[0].section(":::",1,50);
1020     PENDINGOTHER.removeAt(0);   
1021     if( !cmd.isEmpty() && (PBIHASH.contains(cOther) || cOther=="EXTERNAL") ){
1022       //Update the PBI status
1023       if(cOther!="EXTERNAL"){
1024         PBIHASH[cOther].setStatus(InstalledPBI::WORKING);
1025         emit PBIStatusChange(cOther);
1026       }
1027       //Start the process
1028       PMAN->startProcess(ProcessManager::OTHER,cmd);
1029     }else{
1030       cOther.clear();
1031       again=TRUE; //Move to the next pending command
1032     }
1033   }
1034   if(again){ QTimer::singleShot(10,this,SLOT(checkProcesses()) ); }
1035 }
1036 
1037 void PBIBackend::slotProcessFinished(int ID){
1038   bool resync = FALSE;
1039   if(ID == ProcessManager::UPDATE){
1040     if(sUpdate){
1041       //Update stopped during installation of new version: re-install old version
1042        //get metaID of app
1043        /*QString metaID = PBIHASH[cUpdate].metaID;
1044        slotSyncToDatabase(TRUE);
1045        sleep(2);
1046        installApp(QStringList() << metaID); //will install backup version if available*/
1047     }
1048     //Update the PBIHASH for installed versions
1049     resync=TRUE;
1050     cUpdate.clear(); //remove that it is finished
1051     lUpdate.clear();
1052     sUpdate=FALSE;
1053     resync=TRUE;
1054   }else if(ID == ProcessManager::REMOVE){
1055     if(sRemove){
1056       //Removal Cancelled: Re-install the PBI
1057       QString metaID = PBIHASH[cRemove].metaID; //get the metaID
1058       slotSyncToDatabase(TRUE);
1059       sleep(2);
1060       installApp(QStringList() << metaID);
1061     }
1062     sRemove=FALSE;
1063     cRemove.clear(); //remove that it is finished     
1064     lRemove.clear();
1065   }else if(ID == ProcessManager::INSTALL){
1066     //Add XDG commands to the queue
1067     if(sInstall){
1068       //Installation Cancelled: remove the PBI now that the install is complete
1069       QString cmd = generateRemoveCMD(cInstall);
1070       PENDINGREMOVAL << cInstall+":::"+cmd;
1071     }else{ 
1072       // Installation NOT canceled
1073       qDebug() << "Installation Finished:" << cInstall;
1074       if(!keepDownloads){ QFile::remove(dlDir+PBIHASH[cInstall].downloadfile); }
1075       //Generate XDG commands
1076       QString cmd = generateXDGCMD(cInstall, autoXDG, FALSE);
1077       PENDINGOTHER << cInstall+":::"+cmd;
1078     }
1079     sInstall = FALSE;
1080     cInstall.clear(); //remove that it is finished
1081     lInstall.clear();
1082     resync=TRUE; //make sure to reload local files
1083   }else if(ID == ProcessManager::DOWNLOAD){
1084     //Make sure the download was successful
1085     //qDebug() << "dlDir:" << dlDir << "file:" << PBIHASH[cDownload].downloadfile;
1086     if(sDownload){
1087       //Download Cancelled: remove the (partially) downloaded file
1088       QString fPath = dlDir+PBIHASH[cDownload].downloadfile;
1089       if(QFile::exists(fPath)){
1090         QFile::remove(fPath);
1091       }
1092     }else{
1093       //Download not cancelled
1094       if(!QFile::exists(dlDir+PBIHASH[cDownload].downloadfile)){
1095         qDebug() << "Download Error:" << cDownload << PBIHASH[cDownload].downloadfile;
1096         QString title = QString(tr("%1 Download Error:")).arg(PBIHASH[cDownload].name);
1097         QString err = tr("The PBI could not be downloaded, please try again later");
1098         QStringList log = PMAN->getProcessLog(ProcessManager::DOWNLOAD);
1099         emit Error(title,err,log);
1100       }else{
1101         //Now Check to see if an alternate version needs to be removed
1102         QString otherID = isInstalled( PBIHASH[cDownload].metaID );
1103         QString cmd;
1104         if(!otherID.isEmpty()){
1105           cmd = generateRemoveCMD(otherID);
1106           PENDINGINSTALL << otherID+":::"+cmd; //make sure it happens before the install, so put it in the same queue
1107         }
1108         //Now add the installation of this PBI to the queue
1109         cmd = generateInstallCMD(cDownload, PBIHASH[cDownload].downloadfile);
1110         PENDINGINSTALL << cDownload+":::"+cmd;
1111       }
1112     }
1113     sDownload = FALSE;
1114     cDownload.clear(); //remove that it is finished   
1115     lDownload.clear();
1116   }else if(ID == ProcessManager::OTHER){
1117     cOther.clear();       
1118   }
1119   //Get the next processes going
1120   slotSyncToDatabase(resync); //update internal database with/without reading local files again
1121   QTimer::singleShot(0,this,SLOT(checkProcesses()) ); //look for more processes to start
1122 }
1123 
1124void PBIBackend::slotProcessMessage(int ID, QString info){
1125   if(ID == ProcessManager::UPDATE){
1126     //PBIHASH[cUpdate].setStatus(InstalledPBI::UPDATING, dlinfo);
1127     lUpdate = info;
1128     emit PBIStatusChange(cUpdate);
1129   }else if(ID == ProcessManager::DOWNLOAD){
1130     //PBIHASH[cDownload].setStatus(InstalledPBI::DOWNLOADING, dlinfo);
1131     lDownload = info;
1132     emit PBIStatusChange(cDownload);
1133   }else if( ID == ProcessManager::REMOVE){
1134     lRemove = info;
1135     emit PBIStatusChange(cRemove);
1136   }else if( ID == ProcessManager::INSTALL){
1137     lInstall = info;
1138     emit PBIStatusChange(cInstall);
1139   }
1140}
1141
1142void PBIBackend::slotProcessError(int ID, QStringList log){
1143   QString title;
1144   QString name;
1145   QString message;
1146   if(ID == ProcessManager::UPDATE){
1147     if(!sUpdate){ //not stopped manually
1148       if(PBIHASH.contains(cUpdate)){name = PBIHASH[cUpdate].name; }
1149       title = QString(tr("%1 Update Error:")).arg(name); 
1150       message = tr("The update process experienced an error and could not be completed");
1151     }
1152   }
1153   else if(ID == ProcessManager::INSTALL){ 
1154     if(!sInstall){ //not stopped manually
1155       if(APPHASH.contains(cInstall)){name = APPHASH[cInstall].name; }
1156       title = QString(tr("%1 Installation Error:")).arg(name);
1157       message = tr("The installation process experienced an error and could not be completed");
1158     }
1159   }
1160   else if(ID == ProcessManager::REMOVE){ 
1161     if(!sRemove){ //not stopped manually
1162       if(PBIHASH.contains(cRemove)){name = PBIHASH[cRemove].name; }
1163       title = QString(tr("%1 Removal Error:")).arg(name);
1164       message = tr("The removal process experienced an error and could not be completed");
1165     }
1166   }
1167   else if(ID == ProcessManager::DOWNLOAD){ 
1168       //The ProcessFinished function has a bit more robust check for download failures
1169       //       - use it instead to prevent duplicate error messages
1170   }
1171   else if(ID == ProcessManager::OTHER){ 
1172     if(PBIHASH.contains(cOther)){name = PBIHASH[cOther].name; }
1173     title = QString(tr("%1 PBI Error:")).arg(name); 
1174     message = tr("The process experienced an error and could not be completed");
1175   }
1176   if(!title.isEmpty() && !message.isEmpty()){
1177     qDebug() << "Process Error:" << title << log;
1178     emit Error(title,message,log); //send error signal
1179   }
1180   slotProcessFinished(ID); //clean up
1181}
1182
1183 // === Database Synchronization ===
1184 void PBIBackend::slotSyncToDatabase(bool localChanges){
1185   //qDebug() << "Sync Database with local changes:" << localChanges;
1186   //Locally Installed PBI Changes
1187   QStringList currInst = installedList();
1188   QStringList sysList = sysDB->installed();
1189   numInstalled = sysList.length();
1190   //All locally installed applications
1191   for(int i=0; i<sysList.length(); i++){
1192     int index = currInst.indexOf(sysList[i]);
1193     if( index == -1){ //New entry
1194       PBIHASH.insert(sysList[i],InstalledPBI()); //add a blank entry
1195       syncPBI(sysList[i],TRUE); //Now update the info
1196       //Add it to the watcher
1197       watcher->addPath(DBDir+"installed/"+sysList[i]);
1198     }else{  //Existing entry - remove it from the currInst list
1199       if(localChanges){ syncPBI(sysList[i],TRUE); } //synchronize the data with local file changes
1200       else{ updateStatus(sysList[i]); } //just update the status
1201       currInst.removeAt(index);
1202     }     
1203   }
1204   //Non-Installed applications
1205   for(int i=0; i<currInst.length(); i++){
1206     updateStatus(currInst[i]); //update status
1207     InstalledPBI::PBISTATUS stat = PBIHASH[currInst[i]].status;
1208     bool actionPending = (stat != InstalledPBI::NONE) && (stat != InstalledPBI::UPDATEAVAILABLE);
1209     if( !actionPending ){ PBIHASH.remove(currInst[i]); }
1210     else{} //do nothing here
1211   }
1212   emit LocalPBIChanges(); //Let others know that the local PBI's have been updated
1213   //Repo Changes
1214   //qDebug() << "noRepo" << noRepo << "Invalid Repo:" << sysDB->currentRepo() << sysDB->currentRepoInvalid();
1215   if( noRepo || sysDB->currentRepoInvalid() ){
1216     //Change to the first repo available
1217     qDebug() << "Try to find an alternate Repo:";
1218     QStringList repos = sysDB->availableRepos();
1219     if(repos.length() > 0){ 
1220       sysDB->setRepo(repos[0]);
1221     }
1222     syncCurrentRepo();
1223   }else if( CATHASH.isEmpty() && APPHASH.isEmpty() ){
1224     qDebug() << "Load Repo Information";
1225     //If successful, the repo data should only be loaded once
1226     syncCurrentRepo(); 
1227     //If the sync was successful, re-run the PBI sync process to update the license info
1228     if( !APPHASH.isEmpty() ){               
1229       QTimer::singleShot(10,this,SLOT(slotSyncToDatabase())); 
1230     }else{
1231       QTimer::singleShot(60000,this,SLOT(slotSyncToDatabase())); //try again in a minute 
1232     }
1233   }
1234 }
1235 
1236 void PBIBackend::syncPBI(QString pbiID, bool useDB){
1237   //This function is mainly used for initializing the PBIHASH entry
1238   //  but is also used for updating the entry if the local installation settings change (useDB=true)
1239         
1240   //useDB: pull info from the locally installed database (pbiID MUST be installed locally)
1241   //Get the PBI structure
1242   if( !PBIHASH.contains(pbiID) ){ return; }
1243   InstalledPBI pbi = PBIHASH[pbiID];
1244   //Get the associated appID
1245   QString appID = pbi.metaID;
1246   QStringList info = sysDB->installedPbiInfo(pbiID);
1247   if(useDB && !info.isEmpty()){
1248     //Now get additional database info
1249     bool autoUp = sysDB->installedPbiAutoUpdate(pbiID);
1250     bool root = sysDB->installedPbiNeedsRoot(pbiID);
1251     bool desktop = sysDB->installedPbiHasXdgDesktop(info[6]);
1252     bool menu = sysDB->installedPbiHasXdgMenu(info[6]);
1253     //Now add this info to the PBI structure
1254     pbi.name    = info[0];
1255     pbi.version = info[1];
1256     pbi.arch    = info[2];
1257     pbi.mdate   = info[3];
1258     pbi.author  = info[4];
1259     pbi.website = info[5];
1260     if(pbi.website.endsWith("/")){ pbi.website.chop(1); }
1261     pbi.path    = info[6];
1262     pbi.icon    = info[7];
1263     pbi.maintainer = info[8];
1264     pbi.description = info[9];
1265     pbi.fbsdversion = info[10];
1266     if(appID.isEmpty()){ 
1267       appID = Extras::nameToID(pbi.name); 
1268       pbi.metaID = appID;
1269     } //for new item initialization
1270     if(APPHASH.contains(appID)){
1271       pbi.license = APPHASH[appID].license;       
1272     }else{
1273       pbi.license = tr("Unknown");
1274     }
1275     pbi.rootInstall = root;
1276     pbi.autoUpdate  = autoUp;
1277     pbi.desktopIcons= desktop;
1278     pbi.menuIcons   = menu;
1279     //Clean up the mdate to make it human-readable
1280     QDate date(pbi.mdate.left(4).toInt(), pbi.mdate.mid(4,2).toInt(), pbi.mdate.right(2).toInt() );
1281     pbi.mdate =date.toString(Qt::SystemLocaleShortDate); //put it in the current locale format (short version)
1282   }else{
1283     //Pull basic info from the pre-loaded App database instead
1284     // This is for application entries still in a pending state and not fully installed
1285     if(!APPHASH.contains(appID)){ return; }
1286     pbi.name = APPHASH[appID].name;
1287     //Do not change the version or arch - this is usually why the app is in a pending state
1288     pbi.author = APPHASH[appID].author;
1289     pbi.website = APPHASH[appID].website;
1290     pbi.icon = APPHASH[appID].localIcon;
1291     pbi.license = APPHASH[appID].license;
1292     pbi.rootInstall = APPHASH[appID].requiresroot;
1293     pbi.autoUpdate=FALSE;
1294     pbi.desktopIcons=FALSE;
1295     pbi.menuIcons=FALSE;
1296     if(pbi.metaID.isEmpty()){ pbi.metaID = appID; }
1297   }
1298   //Now add this pbi structure back into the hash
1299   PBIHASH.insert(pbiID, pbi); 
1300   //Now update the status
1301   updateStatus(pbiID);
1302 }
1303 
1304 void PBIBackend::slotUpdateAllStatus(){
1305   QStringList pbiID = PBIHASH.keys();
1306   for(int i=0; i<pbiID.length(); i++){
1307     updateStatus(pbiID[i]);     
1308   }
1309 }
1310 
1311 void PBIBackend::updateStatus(QString pbiID){
1312   if(!PBIHASH.contains(pbiID)){ return; }
1313   QString upgrade = upgradeAvailable(pbiID);
1314   QString chk = pbiID+":::"; //for list checking
1315   QString iIndex = PENDINGINSTALL.filter(chk).join(" "); //special case for install list
1316   if(cDownload == pbiID){PBIHASH[pbiID].setStatus(InstalledPBI::DOWNLOADING);}
1317   else if(cInstall == pbiID){PBIHASH[pbiID].setStatus(InstalledPBI::INSTALLING);}
1318   else if(cRemove == pbiID){PBIHASH[pbiID].setStatus(InstalledPBI::REMOVING);}
1319   else if(cUpdate == pbiID){PBIHASH[pbiID].setStatus(InstalledPBI::UPDATING);}
1320   //Look through the pending lists
1321   else if(PENDINGDL.join(" ").contains(chk)){PBIHASH[pbiID].setStatus(InstalledPBI::PENDINGDOWNLOAD);}
1322   else if(!iIndex.isEmpty()){ //install queue can also have special-case removals
1323     if(iIndex.contains("pbi_delete")){ PBIHASH[pbiID].setStatus(InstalledPBI::PENDINGREMOVAL); }
1324     else{ PBIHASH[pbiID].setStatus(InstalledPBI::PENDINGINSTALL); }
1325   }else if(PENDINGREMOVAL.join(" ").contains(chk)){PBIHASH[pbiID].setStatus(InstalledPBI::PENDINGREMOVAL);}
1326   else if(PENDINGUPDATE.join(" ").contains(chk)){PBIHASH[pbiID].setStatus(InstalledPBI::PENDINGUPDATE);}
1327   //else if(PENDINGOTHER.join(" ").contains(chk)){PBIHASH[pbiID].setStatus(InstalledPBI::WORKING);}
1328   else if( !upgrade.isEmpty() ){PBIHASH[pbiID].setStatus(InstalledPBI::UPDATEAVAILABLE); }
1329   else{ PBIHASH[pbiID].setStatus(InstalledPBI::NONE); }
1330 }
1331 
1332 void PBIBackend::syncCurrentRepo(){
1333  //Calling this function will automatically clear and re-populate the APPHASH and CATHASH fields
1334  APPHASH.clear(); CATHASH.clear();
1335  QString mFile = sysDB->metaFilePath(); 
1336  QString iFile = sysDB->indexFilePath();
1337  if( QFile::exists(mFile) && QFile::exists(iFile) ){
1338   //First do the meta data (app/cat info)
1339   QStringList metaFile = Extras::readFile(mFile);
1340   QStringList catsUsed, catsAvail;
1341   //qDebug() << "Sync Meta File Info";
1342   for(int i=0; i<metaFile.length(); i++){
1343     if(metaFile[i].startsWith("App=")){
1344       QStringList info = sysDB->parseAppMetaLine(metaFile[i].section("=",1,50,QString::SectionSkipEmpty));
1345       //qDebug() << "App Meta data:" << info;
1346       if(!info.isEmpty()){ //Make sure the info list is valid
1347         //info[name,category,remoteIcon,author,website,license,apptype,tags,description,requiresroot] (5/1/2013)
1348         //Simplify a couple pieces of info
1349         QString metaID = Extras::nameToID(info[0]);
1350         QString localIcon = sysDB->remoteToLocalIcon(info[0],info[2]);
1351         //Create the container and fill it
1352         MetaPBI app;
1353         app.name=info[0]; app.category=info[1]; app.remoteIcon=info[2];
1354         app.localIcon=localIcon; app.author=info[3]; app.website=info[4];
1355         app.license=info[5]; app.appType=info[6]; app.tags=info[7].toLower().split(","); 
1356         app.description=info[8];
1357         if(info[9]=="true"){ app.requiresroot=TRUE; }
1358         else{ app.requiresroot=FALSE; }
1359         app.dateadded=info[10];
1360         app.maintainer=info[11];
1361         app.shortdescription=info[12];
1362         //Fix the website if needed
1363         if(app.website.endsWith("/")){ app.website.chop(1); }
1364         //Add it to the hash
1365         APPHASH.insert(metaID,app);
1366       }
1367     }else if(metaFile[i].startsWith("Cat=")){
1368       QStringList info = sysDB->parseCatMetaLine(metaFile[i].section("=",1,50,QString::SectionSkipEmpty));
1369       //qDebug() << "Cat Meta Data:" << info;
1370       if(info.length() > 2){ //Make sure the info list is complete
1371         //info[name,remoteicon,description,?] (5/1/2013)
1372         QString catID = Extras::nameToID(info[0]);
1373         QString localIcon = sysDB->remoteToLocalIcon(info[0],info[1]);
1374         //Create the container and fill it
1375         MetaCategory cat;
1376         cat.name=info[0]; cat.remoteIcon=info[1]; cat.localIcon=localIcon; cat.description=info[2];
1377         //Add it to the available list
1378         catsAvail << catID;
1379         //Add it to the hash
1380         CATHASH.insert(catID,cat);
1381       }
1382     }
1383     //qDebug() << " - done with meta line";
1384   }
1385   //qDebug() << "Sync Index File Info";
1386   //Then do the list of available PBI's
1387   QStringList indexFile = Extras::readFile(iFile);
1388   bool sys64 = (sysArch=="amd64");
1389   for(int i=0; i<indexFile.length(); i++){
1390     QStringList info = sysDB->parseIndexLine(indexFile[i]);
1391       //info[name, arch, version, datetime, size, isLatest(true/false)]
1392     if(!info.isEmpty()){
1393       QString metaID = Extras::nameToID(info[0]);
1394       if(APPHASH.contains(metaID)){
1395         bool islatest = (info[5]=="true");
1396         bool is64 = (info[1] == "amd64");
1397         bool save=FALSE;
1398         //Determine whether to save the data or not
1399         if( !sys64 && is64 ){}   // do not save 64-bit apps on a 32-bit system
1400         else if(info[1] == sysArch){ save=TRUE; }  // high priority for identical architecture
1401         else{ //lower priority for 32-bit App on 64-bit system
1402           if(islatest){ 
1403             if(APPHASH[metaID].latestDatetime.isEmpty()){ save=TRUE; } //nothing saved yet, go ahead
1404             else if(APPHASH[metaID].latestArch==sysArch){} // do not save over an app that is the proper arch
1405             else if(Extras::newerDateTime(info[3], APPHASH[metaID].latestDatetime) ){ save=TRUE; } //save over older app
1406           }else{
1407             if(APPHASH[metaID].backupDatetime.isEmpty()){ save=TRUE; } //nothing saved yet, go ahead
1408             else if(APPHASH[metaID].backupArch==sysArch){} // do not save over an app that is the proper arch
1409             else if(Extras::newerDateTime(info[3], APPHASH[metaID].backupDatetime) ){ save=TRUE; } //save over older app
1410           }
1411         }
1412         //Save the data if appropriate
1413         if(save && islatest){
1414           APPHASH[metaID].latestVersion=info[2];
1415           APPHASH[metaID].latestDatetime=info[3];
1416           APPHASH[metaID].latestArch=info[1]; 
1417           APPHASH[metaID].latestSizeK=info[4];
1418           APPHASH[metaID].latestFilename = info[6];
1419         }else if(save){
1420           APPHASH[metaID].backupVersion=info[2];
1421           APPHASH[metaID].backupDatetime=info[3];
1422           APPHASH[metaID].backupArch=info[1]; 
1423           APPHASH[metaID].backupSizeK=info[4];
1424           APPHASH[metaID].backupFilename=info[6];
1425         } 
1426         //if(save){ qDebug() << "APP:" << metaID << info[1] << info[2] << info[3] << info[4] << info[5]; }
1427       } //end check for ID in hash
1428     } //end check for info available
1429   } //end loop over index file
1430   
1431   //Now clean up the APPHASH to remove any entries that do not have a PBI associated with them
1432   QStringList apps = APPHASH.keys();
1433   for(int i=0; i<apps.length(); i++){
1434     if(APPHASH[apps[i]].latestVersion.isEmpty()){
1435       //Make sure there is not a backup version we can use instead
1436       if(APPHASH[apps[i]].backupVersion.isEmpty()){
1437         APPHASH.remove(apps[i]);           
1438       }else{
1439         //Move over the backup to the latest
1440         APPHASH[apps[i]].latestVersion=  APPHASH[apps[i]].backupVersion;
1441         APPHASH[apps[i]].latestDatetime= APPHASH[apps[i]].backupDatetime;
1442         APPHASH[apps[i]].latestArch=     APPHASH[apps[i]].backupArch; 
1443         APPHASH[apps[i]].latestSizeK=    APPHASH[apps[i]].backupSizeK;
1444         APPHASH[apps[i]].latestFilename= APPHASH[apps[i]].backupFilename;
1445         //Now clear the backup
1446         APPHASH[apps[i]].backupVersion.clear();
1447         APPHASH[apps[i]].backupDatetime.clear();
1448         APPHASH[apps[i]].backupArch.clear(); 
1449         APPHASH[apps[i]].backupSizeK.clear();
1450         APPHASH[apps[i]].backupFilename.clear();
1451       }
1452     }else{
1453       //Category being used, remove this category from the list
1454       int catID = catsAvail.indexOf( Extras::nameToID(APPHASH[apps[i]].category) );
1455       if(catID != -1){ catsAvail.removeAt(catID); }
1456     }
1457   }
1458   //Now remove any empty categories (ones left over in catAvail list)
1459   for(int i=0; i<catsAvail.length(); i++){
1460     if( CATHASH.contains(catsAvail[i]) ){
1461       //qDebug() << " - Empty category:" << catsAvail[i];
1462       CATHASH.remove(catsAvail[i]); 
1463     }
1464   }
1465  } // end check for both files existing
1466 
1467  if(APPHASH.isEmpty() && CATHASH.isEmpty()){
1468    numAvailable = -1;
1469    emit NoRepoAvailable();       
1470  }else{
1471    numAvailable = QStringList(APPHASH.keys()).length(); //update the number of apps available
1472    emit RepositoryInfoReady();
1473  }
1474 }
1475 
1476void PBIBackend::startFileSystemWatcher(){
1477   QStringList watched = watcher->directories();
1478   if(!watched.isEmpty()){ watcher->removePaths(watched); }//clear the watcher first
1479   watcher->addPath( DBDir+"installed" ); //look for installed app changes
1480   watcher->addPath( DBDir+"repos" ); //look for repo changes
1481   watcher->addPath( DBDir+"index" ); //look for index/meta file changes         
1482}
1483
1484void PBIBackend::stopFileSystemWatcher(){
1485   QStringList watched = watcher->directories();
1486   if(!watched.isEmpty()){ watcher->removePaths(watched); }//clear the watcher first     
1487}
Note: See TracBrowser for help on using the repository browser.