OSDN Git Service

Correct shutdown on sync being interrupted.
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / NeverNote.java
index 5842a5c..925c908 100644 (file)
@@ -107,7 +107,6 @@ import com.trolltech.qt.gui.QHBoxLayout;
 import com.trolltech.qt.gui.QIcon;
 import com.trolltech.qt.gui.QImage;
 import com.trolltech.qt.gui.QLabel;
-import com.trolltech.qt.gui.QListWidget;
 import com.trolltech.qt.gui.QMainWindow;
 import com.trolltech.qt.gui.QMenu;
 import com.trolltech.qt.gui.QMessageBox;
@@ -143,6 +142,7 @@ import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
 import cx.fbn.nevernote.dialog.DatabaseStatus;
 import cx.fbn.nevernote.dialog.FindDialog;
 import cx.fbn.nevernote.dialog.IgnoreSync;
+import cx.fbn.nevernote.dialog.LogFileDialog;
 import cx.fbn.nevernote.dialog.LoginDialog;
 import cx.fbn.nevernote.dialog.NotebookArchive;
 import cx.fbn.nevernote.dialog.NotebookEdit;
@@ -299,6 +299,12 @@ public class NeverNote extends QMainWindow{
     int                                        tagDeadCount=0;                         // number of consecutive dead times for the tag thread
     int                                        trashDeadCount=0;                       // number of consecutive dead times for the trash thread
     int                                saveThreadDeadCount=0;          // number of consecutive dead times for the save thread
+    boolean                            disableTagThreadCheck=false;
+    boolean                            disableNotebookThreadCheck=false;
+    boolean                            disableTrashThreadCheck=false;
+    boolean                            disableSaveThreadCheck=false;
+    boolean                            disableSyncThreadCheck=false;
+    boolean                            disableIndexThreadCheck=false;
     
     HashMap<String, String>            noteCache;                      // Cash of note content 
     HashMap<String, Boolean>   readOnlyCache;          // List of cashe notes that are read-only
@@ -390,7 +396,9 @@ public class NeverNote extends QMainWindow{
         listManager = new ListManager(conn, logger);
         
                logger.log(logger.EXTREME, "Building index runners & timers");
-        indexRunner = new IndexRunner("indexRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
+        indexRunner = new IndexRunner("indexRunner.log", 
+                       Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
+                       Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
                indexThread = new QThread(indexRunner, "Index Thread");
         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
                indexThread.start();
@@ -407,7 +415,9 @@ public class NeverNote extends QMainWindow{
                                
                logger.log(logger.EXTREME, "Setting sync thread & timers");
                syncThreadsReady=1;
-               syncRunner = new SyncRunner("syncRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
+               syncRunner = new SyncRunner("syncRunner.log", 
+                               Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
+                               Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
                syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
                syncTimer = new QTimer();
                syncTimer.timeout.connect(this, "syncTimer()");
@@ -429,7 +439,9 @@ public class NeverNote extends QMainWindow{
                
                logger.log(logger.EXTREME, "Starting thumnail thread");
                pdfReadyQueue = new ArrayList<String>();
-               thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
+               thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log", 
+                               Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
+                               Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
                thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
                thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
                thumbnailThread.start();
@@ -437,7 +449,7 @@ public class NeverNote extends QMainWindow{
                thumbnailTimer = new QTimer();
                thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
                thumbnailTimer();
-               thumbnailTimer.setInterval(60*1000);  // Thumbnail every minute
+               thumbnailTimer.setInterval(500*1000);  // Thumbnail every minute
                thumbnailTimer.start();
                
                logger.log(logger.EXTREME, "Starting authentication timer");
@@ -774,7 +786,9 @@ public class NeverNote extends QMainWindow{
                         Global.getDatabaseUserPassword(), Global.cipherPassword);
             }
         }
-               DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
+               DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), 
+                               Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
+                               Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
        return dbConn;
     }
     
@@ -785,8 +799,8 @@ public class NeverNote extends QMainWindow{
         try {
                Statement st = conn.getConnection().createStatement();  
                st.execute("shutdown");
-               if (QMessageBox.question(this, "Are you sure"
-                               "Are you sure you wish to encrypt the database?",
+               if (QMessageBox.question(this, tr("Are you sure")
+                               tr("Are you sure you wish to encrypt the database?"),
                                QMessageBox.StandardButton.Yes, 
                                QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
                        ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
@@ -907,17 +921,18 @@ public class NeverNote extends QMainWindow{
                externalFileEditedSaver();
                if (Global.isConnected && Global.synchronizeOnClose()) {
                        setMessage(tr("Performing synchronization before closing."));
+                       syncRunner.syncNeeded = true;
                        syncRunner.addWork("SYNC");
+                       syncRunner.addWork("STOP");
+               } else {
+                       syncRunner.addWork("STOP");
+                       syncRunner.keepRunning = false;
                }
                setMessage("Closing Program.");
                threadMonitorTimer.stop();
 
-               syncRunner.addWork("STOP");
-               syncRunner.keepRunning = false;
                thumbnailRunner.addWork("STOP");
-               syncRunner.keepRunning = false;
                indexRunner.addWork("STOP");
-               syncRunner.keepRunning = false;
                saveNote();
                listManager.stop();
                saveWindowState();
@@ -963,15 +978,18 @@ public class NeverNote extends QMainWindow{
                                indexRunner.thread().join(50);
                        if (!indexRunner.thread().isAlive())
                                logger.log(logger.MEDIUM, "Index thread has stopped");
-                       else
-                               logger.log(logger.MEDIUM, "Index thread still running - bypassing");
+                       else {
+                               logger.log(logger.MEDIUM, "Index thread still running - interrupting");
+                               indexRunner.thread().interrupt();
+                       }
                } catch (InterruptedException e1) {
                        e1.printStackTrace();
                }
                if (!syncRunner.isIdle()) {
                        try {
                                logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
-                               syncThread.join();
+                               System.out.println(tr("Synchronizing.  Please be patient."));
+                               syncThread.join(0);
                                logger.log(logger.MEDIUM, "Sync thread has stopped");
                        } catch (InterruptedException e1) {
                                e1.printStackTrace();
@@ -984,6 +1002,12 @@ public class NeverNote extends QMainWindow{
                if (decryptOnShutdown) {
                        decryptOnShutdown();
                }
+               try {
+                       Global.getFileManager().purgeResDirectory(false);
+               } catch (InitializationException e) {
+                       System.out.println(tr("Empty res directory purge failed"));
+                       e.printStackTrace();
+               }
                logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
        }
 
@@ -1032,6 +1056,7 @@ public class NeverNote extends QMainWindow{
                syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
                syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
                syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
+               syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
                
                syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
        }
@@ -1432,7 +1457,8 @@ public class NeverNote extends QMainWindow{
                if (guid.equalsIgnoreCase("STACK")) {
                        conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
                        for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
-                               if (listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
+                               if (listManager.getNotebookIndex().get(j).getStack() != null && 
+                                       listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
                                                listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
                        }
                        conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
@@ -2391,6 +2417,7 @@ public class NeverNote extends QMainWindow{
        @SuppressWarnings("unused")
        private void databaseStatus() {
                waitCursor(true);
+               indexRunner.interrupt = true;
                int dirty = conn.getNoteTable().getDirtyCount();
                int unindexed = conn.getNoteTable().getUnindexedCount();
                DatabaseStatus status = new DatabaseStatus();
@@ -2454,15 +2481,8 @@ public class NeverNote extends QMainWindow{
        @SuppressWarnings("unused")
        private void logger() {
                logger.log(logger.HIGH, "Entering NeverNote.logger");
-               QDialog dialog = new QDialog(this);
-               QHBoxLayout layout = new QHBoxLayout();
-               QListWidget textBox = new QListWidget();
-               layout.addWidget(textBox);
-               textBox.addItems(emitLog);
-               
-               dialog.setLayout(layout);
-               dialog.setWindowTitle(tr("Mesasge Log"));
-               dialog.show();
+               LogFileDialog dialog = new LogFileDialog(emitLog);
+               dialog.exec();
                logger.log(logger.HIGH, "Leaving NeverNote.logger");
        }
        // Menu option "help/about" was selected
@@ -2564,8 +2584,10 @@ public class NeverNote extends QMainWindow{
                }
                
                
-               if (Global.version.equals(version))
-                       return;
+               for (String validVersion : Global.validVersions) {
+                       if (version.equals(validVersion))
+                               return;
+               }
                
                UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
                dialog.exec();
@@ -3110,56 +3132,67 @@ public class NeverNote extends QMainWindow{
                } catch (FileNotFoundException e) {
                        // File not found, so we'll just get empty strings anyway. 
                }
+
+               if (Global.getProxyValue("url").equals("")) {
+                       System.setProperty("http.proxyHost","") ;
+                       System.setProperty("http.proxyPort", "") ;
+                       System.setProperty("https.proxyHost","") ;
+                       System.setProperty("https.proxyPort", "") ;         
+               } else {
+                       // PROXY
+                       System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
+                       System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
+                       System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
+                       System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
+                       if (Global.getProxyValue("userid").equals("")) {
+                               Authenticator.setDefault(new Authenticator() {
+                       @Override
+                       protected PasswordAuthentication getPasswordAuthentication() {
+                               return new
+                               PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
+                               }
+                       });
+               }
+       }
+
+               syncRunner.userStoreUrl = Global.userStoreUrl;
+               syncRunner.noteStoreUrl = Global.noteStoreUrl;
+               syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
+
                String userid = aes.getUserid();
                String password = aes.getPassword();
                if (!userid.equals("") && !password.equals("")) {
                Global.username = userid;
                Global.password = password;
+                       syncRunner.username = Global.username;
+                       syncRunner.password = Global.password;
+               syncRunner.enConnect();
                }               
 
-        // Show the login dialog box
-               if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
-                       LoginDialog login = new LoginDialog();
-                       login.exec();
+               Global.isConnected = syncRunner.isConnected;
                
-                       if (!login.okPressed()) {
-                               return;
-                       }
+               if (!Global.isConnected) {
+                       // Show the login dialog box
+                       if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
+                               LoginDialog login = new LoginDialog();
+                               login.exec();
+               
+                               if (!login.okPressed()) {
+                                       return;
+                               }
         
-                       Global.username = login.getUserid();
-                       Global.password = login.getPassword();
+                               Global.username = login.getUserid();
+                               Global.password = login.getPassword();
+                       }
+                       syncRunner.username = Global.username;
+                       syncRunner.password = Global.password;
+                       syncRunner.enConnect();
+                       Global.isConnected = syncRunner.isConnected;
                }
-               syncRunner.username = Global.username;
-               syncRunner.password = Global.password;
-               syncRunner.userStoreUrl = Global.userStoreUrl;
-               syncRunner.noteStoreUrl = Global.noteStoreUrl;
-               syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
                
-           if (Global.getProxyValue("url").equals("")) {
-               System.setProperty("http.proxyHost","") ;
-               System.setProperty("http.proxyPort", "") ;
-               System.setProperty("https.proxyHost","") ;
-               System.setProperty("https.proxyPort", "") ;         
-           } else {
-                       // PROXY
-               System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
-               System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
-               System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
-               System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
-        
-               if (Global.getProxyValue("userid").equals("")) {
-                       Authenticator.setDefault(new Authenticator() {
-                               @Override
-                               protected PasswordAuthentication getPasswordAuthentication() {
-                                       return new
-                                       PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
-                                       }});
-                       }
-               }
-               
-               
-               syncRunner.enConnect();
-               Global.isConnected = syncRunner.isConnected;
+               if (!Global.isConnected)
+                       return;
                setupOnlineMenu();
                setupConnectMenuOptions();
                logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
@@ -3385,6 +3418,7 @@ public class NeverNote extends QMainWindow{
                        }
                }
        }               
+       showColumns();
        scrollToGuid(currentNoteGuid);
                logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
     }
@@ -3940,6 +3974,7 @@ public class NeverNote extends QMainWindow{
     @SuppressWarnings("unused")
        private void setNoteDirty() {
                logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
+               
                // Find if the note is being edited externally.  If it is, update it.
                if (externalWindows.containsKey(currentNoteGuid)) {
                        QTextCodec codec = QTextCodec.codecForName("UTF-8");
@@ -5072,7 +5107,7 @@ public class NeverNote extends QMainWindow{
                        syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
                        
                        if (syncThreadsReady > 0) {
-                               indexRunner.interrupt = true;
+                               thumbnailRunner.interrupt = true;
                                saveNoteIndexWidth();
                                saveNoteColumnPositions();
                                if (syncRunner.addWork("SYNC")) {
@@ -5177,6 +5212,7 @@ public class NeverNote extends QMainWindow{
                if (syncRunning) 
                        return;
                if (!indexDisabled && indexRunner.idle) { 
+                       thumbnailRunner.interrupt = true;
                        indexRunner.addWork("SCAN");
                }
                logger.log(logger.EXTREME, "Leaving neverNote index timer");
@@ -5211,47 +5247,64 @@ public class NeverNote extends QMainWindow{
                alive = listManager.threadCheck(Global.tagCounterThreadId);
                if (!alive) {
                        tagDeadCount++;
-                       if (tagDeadCount > MAX)
+                       if (tagDeadCount > MAX && !disableTagThreadCheck) {
                                QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died.  I recommend "+
                                "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
+                               disableTagThreadCheck = true;
+                       }
                } else
                        tagDeadCount=0;
                
                alive = listManager.threadCheck(Global.notebookCounterThreadId);
                if (!alive) {
                        notebookThreadDeadCount++;
-                       QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died.  I recommend "+
-                       "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
+                       if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
+                               QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died.  I recommend "+
+                                       "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
+                               disableNotebookThreadCheck=true;
+                       }
                } else
                        notebookThreadDeadCount=0;
                
                alive = listManager.threadCheck(Global.trashCounterThreadId);
                if (!alive) {
                        trashDeadCount++;
-                       QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died.  I recommend "+
-                       "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
+                       if (trashDeadCount > MAX && !disableTrashThreadCheck) {
+                               QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died.  I recommend "+
+                                       "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
+                               disableTrashThreadCheck = true;
+                       }
                } else
                        trashDeadCount = 0;
 
                alive = listManager.threadCheck(Global.saveThreadId);
                if (!alive) {
                        saveThreadDeadCount++;
-                       QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died.  I recommend "+
-                       "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
+                       if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
+                               QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died.  I recommend "+
+                                       "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
+                               disableSaveThreadCheck = true;
+                       }
                } else
                        saveThreadDeadCount=0;
 
                if (!syncThread.isAlive()) {
                        syncThreadDeadCount++;
-                       QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died.  I recommend "+
-                       "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
+                       if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
+                               QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died.  I recommend "+
+                                       "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
+                               disableSyncThreadCheck = true;
+                       }
                } else
                        syncThreadDeadCount=0;
 
                if (!indexThread.isAlive()) {
                        indexThreadDeadCount++;
-                       QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died.  I recommend "+
-                       "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
+                       if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
+                               QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died.  I recommend "+
+                                       "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
+                               disableIndexThreadCheck = true;
+                       }
                } else
                        indexThreadDeadCount=0;
 
@@ -5259,11 +5312,8 @@ public class NeverNote extends QMainWindow{
        }
 
        private void thumbnailTimer() {
-               if (Global.enableThumbnails() && conn.getNoteTable().getThumbnailNeededCount() > 1) {
-                       thumbnailTimer.setInterval(10*1000);
+               if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
                        thumbnailRunner.addWork("SCAN");
-               } else {
-                       thumbnailTimer.setInterval(60*1000);
                }
        }
        
@@ -5413,7 +5463,7 @@ public class NeverNote extends QMainWindow{
                
        ImportData noteReader = new ImportData(conn, false);
        String fileName = fd.selectedFiles().get(0);
-       saveLastPath.substring(0,fileName.lastIndexOf("/"));
+//     saveLastPath.substring(0,fileName.lastIndexOf("/"));
 
        if (!fileName.endsWith(".nnex"))
                fileName = fileName +".nnex";