OSDN Git Service

Change spell check defaults and allow options to be changed without a restart.
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / gui / BrowserWindow.java
1 /*\r
2  * This file is part of NeverNote \r
3  * Copyright 2009 Randy Baumgarte\r
4  * \r
5  * This file may be licensed under the terms of of the\r
6  * GNU General Public License Version 2 (the ``GPL'').\r
7  *\r
8  * Software distributed under the License is distributed\r
9  * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either\r
10  * express or implied. See the GPL for the specific language\r
11  * governing rights and limitations.\r
12  *\r
13  * You should have received a copy of the GPL along with this\r
14  * program. If not, go to http://www.gnu.org/licenses/gpl.html\r
15  * or write to the Free Software Foundation, Inc.,\r
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r
17  *\r
18  */\r
19 \r
20 package cx.fbn.nevernote.gui;\r
21 \r
22 import java.io.File;\r
23 import java.io.FileNotFoundException;\r
24 import java.io.IOException;\r
25 import java.net.FileNameMap;\r
26 import java.net.URI;\r
27 import java.net.URLConnection;\r
28 import java.security.MessageDigest;\r
29 import java.security.NoSuchAlgorithmException;\r
30 import java.text.SimpleDateFormat;\r
31 import java.util.ArrayList;\r
32 import java.util.Calendar;\r
33 import java.util.Collections;\r
34 import java.util.Date;\r
35 import java.util.GregorianCalendar;\r
36 import java.util.HashMap;\r
37 import java.util.List;\r
38 import java.util.Locale;\r
39 \r
40 import org.apache.commons.lang.StringUtils;\r
41 \r
42 import com.evernote.edam.limits.Constants;\r
43 import com.evernote.edam.type.Data;\r
44 import com.evernote.edam.type.Note;\r
45 import com.evernote.edam.type.Notebook;\r
46 import com.evernote.edam.type.Resource;\r
47 import com.evernote.edam.type.ResourceAttributes;\r
48 import com.evernote.edam.type.Tag;\r
49 import com.swabunga.spell.engine.Configuration;\r
50 import com.swabunga.spell.engine.SpellDictionary;\r
51 import com.swabunga.spell.engine.SpellDictionaryHashMap;\r
52 import com.swabunga.spell.engine.Word;\r
53 import com.swabunga.spell.event.SpellCheckEvent;\r
54 import com.swabunga.spell.event.SpellCheckListener;\r
55 import com.swabunga.spell.event.SpellChecker;\r
56 import com.swabunga.spell.event.StringWordTokenizer;\r
57 import com.trolltech.qt.core.QByteArray;\r
58 import com.trolltech.qt.core.QDataStream;\r
59 import com.trolltech.qt.core.QDateTime;\r
60 import com.trolltech.qt.core.QEvent;\r
61 import com.trolltech.qt.core.QEvent.Type;\r
62 import com.trolltech.qt.core.QFile;\r
63 import com.trolltech.qt.core.QFileSystemWatcher;\r
64 import com.trolltech.qt.core.QIODevice;\r
65 import com.trolltech.qt.core.QMimeData;\r
66 import com.trolltech.qt.core.QUrl;\r
67 import com.trolltech.qt.core.Qt.Key;\r
68 import com.trolltech.qt.core.Qt.KeyboardModifier;\r
69 import com.trolltech.qt.core.Qt.KeyboardModifiers;\r
70 import com.trolltech.qt.gui.QAction;\r
71 import com.trolltech.qt.gui.QApplication;\r
72 import com.trolltech.qt.gui.QCalendarWidget;\r
73 import com.trolltech.qt.gui.QClipboard;\r
74 import com.trolltech.qt.gui.QColor;\r
75 import com.trolltech.qt.gui.QComboBox;\r
76 import com.trolltech.qt.gui.QDateEdit;\r
77 import com.trolltech.qt.gui.QDesktopServices;\r
78 import com.trolltech.qt.gui.QFileDialog;\r
79 import com.trolltech.qt.gui.QFileDialog.AcceptMode;\r
80 import com.trolltech.qt.gui.QFileDialog.FileMode;\r
81 import com.trolltech.qt.gui.QFontDatabase;\r
82 import com.trolltech.qt.gui.QFormLayout;\r
83 import com.trolltech.qt.gui.QGridLayout;\r
84 import com.trolltech.qt.gui.QHBoxLayout;\r
85 import com.trolltech.qt.gui.QIcon;\r
86 import com.trolltech.qt.gui.QImage;\r
87 import com.trolltech.qt.gui.QKeyEvent;\r
88 import com.trolltech.qt.gui.QKeySequence;\r
89 import com.trolltech.qt.gui.QLabel;\r
90 import com.trolltech.qt.gui.QLineEdit;\r
91 import com.trolltech.qt.gui.QListWidgetItem;\r
92 import com.trolltech.qt.gui.QMatrix;\r
93 import com.trolltech.qt.gui.QMessageBox;\r
94 import com.trolltech.qt.gui.QPushButton;\r
95 import com.trolltech.qt.gui.QShortcut;\r
96 import com.trolltech.qt.gui.QTimeEdit;\r
97 import com.trolltech.qt.gui.QToolButton;\r
98 import com.trolltech.qt.gui.QToolButton.ToolButtonPopupMode;\r
99 import com.trolltech.qt.gui.QVBoxLayout;\r
100 import com.trolltech.qt.gui.QWidget;\r
101 import com.trolltech.qt.network.QNetworkRequest;\r
102 import com.trolltech.qt.webkit.QWebPage;\r
103 import com.trolltech.qt.webkit.QWebPage.WebAction;\r
104 import com.trolltech.qt.webkit.QWebSettings;\r
105 import com.trolltech.qt.webkit.QWebView;\r
106 \r
107 import cx.fbn.nevernote.Global;\r
108 import cx.fbn.nevernote.dialog.EnCryptDialog;\r
109 import cx.fbn.nevernote.dialog.EnDecryptDialog;\r
110 import cx.fbn.nevernote.dialog.GeoDialog;\r
111 import cx.fbn.nevernote.dialog.InsertLinkDialog;\r
112 import cx.fbn.nevernote.dialog.SpellCheck;\r
113 import cx.fbn.nevernote.dialog.TableDialog;\r
114 import cx.fbn.nevernote.dialog.TagAssign;\r
115 import cx.fbn.nevernote.evernote.EnCrypt;\r
116 import cx.fbn.nevernote.signals.NoteResourceSignal;\r
117 import cx.fbn.nevernote.signals.NoteSignal;\r
118 import cx.fbn.nevernote.sql.DatabaseConnection;\r
119 import cx.fbn.nevernote.utilities.ApplicationLogger;\r
120 import cx.fbn.nevernote.utilities.FileUtils;\r
121 \r
122 public class BrowserWindow extends QWidget {\r
123 \r
124         public final QLineEdit titleLabel;\r
125         private final QLineEdit urlText;\r
126         private final QLabel authorLabel;\r
127         private final QLineEdit authorText;\r
128         private final QComboBox geoBox;\r
129         public final TagLineEdit tagEdit;\r
130         public final QLabel tagLabel;\r
131         private final QPushButton urlLabel;\r
132         private final QLabel alteredLabel;\r
133         private final QDateEdit alteredDate;\r
134         private final QTimeEdit alteredTime;\r
135         private final QDateEdit createdDate;\r
136         private final QTimeEdit createdTime;\r
137         private final QLabel subjectLabel;\r
138         private final QDateEdit subjectDate;\r
139         private final QTimeEdit subjectTime;\r
140         public final QComboBox notebookBox;\r
141         private final QLabel notebookLabel;\r
142         private final QLabel createdLabel;\r
143         public final QComboBox fontSize;\r
144         public final QAction    fontSizeAction;\r
145         private boolean extendedOn;\r
146         public boolean buttonsVisible;\r
147         private final String iconPath = new String("classpath:cx/fbn/nevernote/icons/");\r
148         private final ContentView browser;\r
149         private List<Tag> allTags;\r
150         private List<String> currentTags;\r
151         public NoteSignal noteSignal;\r
152         private List<Notebook> notebookList;\r
153         private Note currentNote;\r
154         private String saveNoteTitle;\r
155         private String saveTagList;\r
156         private boolean insideList;\r
157 //      private String selectedText;\r
158         private final DatabaseConnection conn;\r
159         private final QCalendarWidget createdCalendarWidget;\r
160         private final QCalendarWidget alteredCalendarWidget;\r
161         private final QCalendarWidget subjectCalendarWidget;\r
162 \r
163         public final QPushButton undoButton;\r
164         public final QAction    undoAction;\r
165         public final QPushButton redoButton;\r
166         public final QAction    redoAction;\r
167         public final QPushButton cutButton;\r
168         public final QAction    cutAction;\r
169         public final QPushButton copyButton;\r
170         public final QAction    copyAction;\r
171         public final QPushButton pasteButton;\r
172         public final QAction    pasteAction;\r
173         public final QPushButton boldButton;\r
174         public final QAction    boldAction;\r
175         public final QPushButton underlineButton;\r
176         public final QAction    underlineAction;\r
177         public final QPushButton italicButton;\r
178         public final QAction    italicAction;\r
179         public final Signal0 focusLost;\r
180         public final NoteResourceSignal resourceSignal;\r
181 \r
182         public QPushButton rightAlignButton;\r
183         public final QAction    rightAlignAction;\r
184         public QPushButton leftAlignButton;\r
185         public final QAction    leftAlignAction;\r
186         public QPushButton centerAlignButton;\r
187         public final QAction    centerAlignAction;\r
188 \r
189         public final QPushButton strikethroughButton;\r
190         public final QAction    strikethroughAction;\r
191         public final QPushButton hlineButton;\r
192         public final QAction    hlineAction;\r
193         public final QPushButton indentButton;\r
194         public final QAction    indentAction;\r
195         public final QPushButton outdentButton;\r
196         public final QAction    outdentAction;\r
197         public final QPushButton bulletListButton;\r
198         public final QAction    bulletListAction;\r
199         public final QPushButton numberListButton;\r
200         public final QAction    numberListAction;\r
201         public final QPushButton spellCheckButton;\r
202         public final QAction    spellCheckAction;\r
203         public final QPushButton todoButton;\r
204         public final QAction    todoAction;\r
205 \r
206         public final QShortcut focusTitleShortcut;\r
207         public final QShortcut focusTagShortcut;\r
208         public final QShortcut focusNoteShortcut;\r
209         public final QShortcut focusUrlShortcut;\r
210         public final QShortcut focusAuthorShortcut;\r
211         \r
212         public EditorButtonBar buttonLayout;\r
213         public final QComboBox fontList;\r
214         public final QAction    fontListAction;\r
215         public final QToolButton fontColor;\r
216         public final QAction    fontColorAction;\r
217         private final ColorMenu fontColorMenu;\r
218         public final QToolButton fontHilight;\r
219         public final QAction    fontHilightAction;\r
220         private final ColorMenu fontHilightColorMenu;\r
221         public final QFileSystemWatcher fileWatcher;\r
222         public int cursorPosition;\r
223         private boolean forceTextPaste = false;\r
224         private String selectedFile;\r
225         private String currentHyperlink;\r
226         public boolean keepPDFNavigationHidden;\r
227         private final ApplicationLogger logger;\r
228         SpellDictionary dictionary;\r
229     SpellDictionary userDictionary;\r
230     SpellChecker spellChecker;\r
231     SuggestionListener spellListener;\r
232         private final HashMap<String,Integer> previewPageList; \r
233         \r
234         \r
235         public static class SuggestionListener implements SpellCheckListener {\r
236                 public boolean abortSpellCheck = false;\r
237                 public boolean errorsFound = false;\r
238                 private final SpellCheck                spellCheckDialog;\r
239                 \r
240                 \r
241                 private final BrowserWindow parent;\r
242                 public SuggestionListener(BrowserWindow parent, SpellChecker checker) {\r
243                         this.parent = parent;\r
244                         spellCheckDialog = new SpellCheck(checker);\r
245                 }\r
246                 public void spellingError(SpellCheckEvent event) {\r
247                         System.out.println("**" +event.getInvalidWord());\r
248                         errorsFound = true;\r
249                         spellCheckDialog.setWord(event.getInvalidWord());\r
250 \r
251                     List<Word> suggestions = event.getSuggestions();\r
252                     spellCheckDialog.clearSuggestions();\r
253                     if (!suggestions.isEmpty()) {\r
254 //                     spellCheckDialog.setCurrentSuggestion(suggestions.get(0).getWord());\r
255                        for (int i=0; i<suggestions.size(); i++) {\r
256                           spellCheckDialog.addSuggestion(suggestions.get(i).getWord());\r
257                        }\r
258                        spellCheckDialog.setSelectedSuggestion(0);\r
259                     }\r
260                     spellCheckDialog.exec();\r
261                     if (spellCheckDialog.cancelPressed()) {\r
262                         abortSpellCheck = true;\r
263                         event.cancel();\r
264                         return;\r
265                     }\r
266                     if (spellCheckDialog.replacePressed()) {\r
267                         QClipboard clipboard = QApplication.clipboard();\r
268                         clipboard.setText(spellCheckDialog.getReplacementWord()); \r
269                         parent.pasteClicked();\r
270                     }\r
271                     event.cancel();\r
272                  }\r
273         }\r
274 \r
275         \r
276         \r
277         public BrowserWindow(DatabaseConnection c) {\r
278                 logger = new ApplicationLogger("browser.log");\r
279                 logger.log(logger.HIGH, "Setting up browser");\r
280                 \r
281                 fileWatcher = new QFileSystemWatcher();\r
282 //              fileWatcher.fileChanged.connect(this, "fileChanged(String)");\r
283                 noteSignal = new NoteSignal();\r
284                 titleLabel = new QLineEdit();\r
285                 titleLabel.setMaxLength(Constants.EDAM_NOTE_TITLE_LEN_MAX);\r
286                 urlText = new QLineEdit();\r
287                 authorText = new QLineEdit();\r
288                 geoBox = new QComboBox();\r
289                 urlLabel = new QPushButton();\r
290                 urlLabel.clicked.connect(this, "sourceUrlClicked()");\r
291                 authorLabel = new QLabel();\r
292                 conn = c;\r
293                 \r
294                 focusLost = new Signal0();\r
295 \r
296                 tagEdit = new TagLineEdit(allTags);\r
297                 tagLabel = new QLabel("Tags:");\r
298                 tagEdit.focusLost.connect(this, "modifyTagsTyping()");\r
299 \r
300                 createdCalendarWidget = new QCalendarWidget();\r
301                 createdDate = new QDateEdit();\r
302                 createdDate.setDisplayFormat(Global.getDateFormat());\r
303                 createdDate.setCalendarPopup(true);\r
304                 createdDate.setCalendarWidget(createdCalendarWidget);\r
305                 createdTime = new QTimeEdit();\r
306                 createdDate.dateChanged.connect(this, "createdChanged()");\r
307                 createdTime.timeChanged.connect(this, "createdChanged()");\r
308 \r
309                 alteredCalendarWidget = new QCalendarWidget();\r
310                 alteredDate = new QDateEdit();\r
311                 alteredDate.setDisplayFormat(Global.getDateFormat());\r
312                 alteredDate.setCalendarPopup(true);\r
313                 alteredDate.setCalendarWidget(alteredCalendarWidget);\r
314                 alteredTime = new QTimeEdit();\r
315                 alteredLabel = new QLabel("Altered:");\r
316                 alteredDate.dateChanged.connect(this, "alteredChanged()");\r
317                 alteredTime.timeChanged.connect(this, "alteredChanged()");\r
318 \r
319                 subjectCalendarWidget = new QCalendarWidget();\r
320                 subjectDate = new QDateEdit();\r
321                 subjectDate.setDisplayFormat(Global.getDateFormat());\r
322                 subjectDate.setCalendarPopup(true);\r
323                 subjectDate.setCalendarWidget(subjectCalendarWidget);\r
324                 subjectTime = new QTimeEdit();\r
325                 subjectLabel = new QLabel(tr("Subject Date:"));\r
326                 subjectDate.dateChanged.connect(this, "subjectDateTimeChanged()");\r
327                 subjectTime.timeChanged.connect(this, "subjectDateTimeChanged()");\r
328                 authorText.textChanged.connect(this, "authorChanged()");\r
329                 urlText.textChanged.connect(this, "sourceUrlChanged()");\r
330 \r
331                 notebookBox = new QComboBox();\r
332                 notebookLabel = new QLabel(tr("Notebook"));\r
333                 createdLabel = new QLabel(tr("Created:"));\r
334                 // selectedText = new String();\r
335 \r
336                 urlLabel.setVisible(false);\r
337                 urlText.setVisible(false);\r
338                 authorLabel.setVisible(false);\r
339                 \r
340                 geoBox.setVisible(false);\r
341                 geoBox.addItem(new QIcon(iconPath+"globe.png"), "");\r
342                 geoBox.addItem(new String(tr("Set")));\r
343                 geoBox.addItem(new String(tr("Clear")));\r
344                 geoBox.addItem(new String(tr("View On Map")));\r
345                 geoBox.activated.connect(this, "geoBoxChanged()");\r
346                 \r
347                 authorText.setVisible(false);\r
348                 createdDate.setVisible(false);\r
349                 alteredLabel.setVisible(false);\r
350                 //notebookBox.setVisible(false);\r
351                 notebookLabel.setVisible(false);\r
352                 createdLabel.setVisible(false);\r
353                 createdTime.setVisible(false);\r
354                 alteredDate.setVisible(false);\r
355                 alteredTime.setVisible(false);\r
356                 subjectLabel.setVisible(false);\r
357                 subjectDate.setVisible(false);\r
358                 subjectTime.setVisible(false);\r
359                 extendedOn = false;\r
360                 buttonsVisible = true;\r
361                 setAcceptDrops(true);\r
362 \r
363                 browser = new ContentView(this);\r
364                 browser.page().setLinkDelegationPolicy(\r
365                                 QWebPage.LinkDelegationPolicy.DelegateAllLinks);\r
366                 browser.linkClicked.connect(this, "linkClicked(QUrl)");\r
367                 currentHyperlink = "";\r
368                 \r
369                 QVBoxLayout v = new QVBoxLayout();\r
370                 QFormLayout notebookLayout = new QFormLayout();\r
371                 QGridLayout dateLayout = new QGridLayout();\r
372                 titleLabel.setReadOnly(false);\r
373                 titleLabel.editingFinished.connect(this, "titleEdited()");\r
374                 browser.page().contentsChanged.connect(this, "contentChanged()");\r
375                 browser.page().selectionChanged.connect(this, "selectionChanged()");\r
376                 browser.page().mainFrame().javaScriptWindowObjectCleared.connect(this,\r
377                                 "exposeToJavascript()");\r
378 \r
379                 notebookBox.activated.connect(this, "notebookChanged()");\r
380                 resourceSignal = new NoteResourceSignal();\r
381                 \r
382                 QHBoxLayout tagLayout = new QHBoxLayout();\r
383                 v.addWidget(titleLabel, 0);\r
384                 notebookLayout.addRow(notebookLabel, notebookBox);\r
385                 tagLayout.addLayout(notebookLayout, 0);\r
386                 tagLayout.stretch(4);\r
387                 tagLayout.addWidget(tagLabel, 0);\r
388                 tagLayout.addWidget(tagEdit, 1);\r
389                 v.addLayout(tagLayout);\r
390 \r
391                 QHBoxLayout urlLayout = new QHBoxLayout();\r
392                 urlLayout.addWidget(urlLabel, 0);\r
393                 urlLayout.addWidget(urlText, 0);\r
394                 v.addLayout(urlLayout);\r
395 \r
396                 QHBoxLayout authorLayout = new QHBoxLayout();\r
397                 authorLayout.addWidget(authorLabel, 0);\r
398                 authorLayout.addWidget(authorText, 0);\r
399                 authorLayout.addWidget(geoBox);\r
400                 v.addLayout(authorLayout);\r
401 \r
402                 dateLayout.addWidget(createdLabel, 0, 0);\r
403                 dateLayout.addWidget(createdDate, 0, 1);\r
404                 dateLayout.addWidget(createdTime, 0, 2);\r
405                 dateLayout.setColumnStretch(9, 100);\r
406                 dateLayout.addWidget(alteredLabel, 0, 3);\r
407                 dateLayout.addWidget(alteredDate, 0, 4);\r
408                 dateLayout.addWidget(alteredTime, 0, 5);\r
409                 dateLayout.addWidget(subjectLabel, 0, 6);\r
410                 dateLayout.addWidget(subjectDate, 0, 7);\r
411                 dateLayout.addWidget(subjectTime, 0, 8);\r
412                 v.addLayout(dateLayout, 0);\r
413 \r
414                 undoButton = newEditorButton("undo", tr("Undo Change"));\r
415                 redoButton = newEditorButton("redo", tr("Redo Change"));\r
416                 cutButton = newEditorButton("cut", tr("Cut"));\r
417                 copyButton = newEditorButton("copy", tr("Copy"));\r
418                 pasteButton = newEditorButton("paste", tr("Paste"));\r
419                 boldButton = newEditorButton("bold", tr("Bold"));\r
420                 underlineButton = newEditorButton("underline", tr("Underline"));\r
421                 italicButton = newEditorButton("italic", tr("Italic"));\r
422 \r
423                 rightAlignButton = newEditorButton("justifyRight", tr("Right Align"));\r
424                 leftAlignButton = newEditorButton("justifyLeft", tr("Left Align"));\r
425                 centerAlignButton = newEditorButton("justifyCenter", tr("Center Align"));\r
426 \r
427                 strikethroughButton = newEditorButton("strikethrough", tr("Strikethrough"));\r
428                 hlineButton = newEditorButton("hline", tr("Insert Horizontal Line"));\r
429                 indentButton = newEditorButton("indent", tr("Shift Right"));\r
430                 outdentButton = newEditorButton("outdent", tr("Shift Left"));\r
431                 bulletListButton = newEditorButton("bulletList", tr("Bullet List"));\r
432                 numberListButton = newEditorButton("numberList", tr("Number List"));\r
433                 spellCheckButton = newEditorButton("spellCheck", tr("Spell Check"));\r
434                 todoButton = newEditorButton("todo", tr("To-do"));\r
435 \r
436                 \r
437                 buttonLayout = new EditorButtonBar();\r
438                 v.addWidget(buttonLayout);\r
439                 \r
440                 undoAction = buttonLayout.addWidget(undoButton);\r
441                 buttonLayout.toggleUndoVisible.triggered.connect(this, "toggleUndoVisible(Boolean)");\r
442                 redoAction = buttonLayout.addWidget(redoButton);\r
443                 buttonLayout.toggleRedoVisible.triggered.connect(this, "toggleRedoVisible(Boolean)");\r
444                 \r
445                 buttonLayout.addWidget(newSeparator());\r
446                 cutAction = buttonLayout.addWidget(cutButton);\r
447                 buttonLayout.toggleCutVisible.triggered.connect(this, "toggleCutVisible(Boolean)");\r
448                 copyAction = buttonLayout.addWidget(copyButton);\r
449                 buttonLayout.toggleCopyVisible.triggered.connect(this, "toggleCopyVisible(Boolean)");\r
450                 pasteAction = buttonLayout.addWidget(pasteButton);\r
451                 buttonLayout.togglePasteVisible.triggered.connect(this, "togglePasteVisible(Boolean)");\r
452 \r
453                 buttonLayout.addWidget(newSeparator());\r
454                 boldAction = buttonLayout.addWidget(boldButton);\r
455                 buttonLayout.toggleBoldVisible.triggered.connect(this, "toggleBoldVisible(Boolean)");\r
456                 italicAction = buttonLayout.addWidget(italicButton);\r
457                 buttonLayout.toggleItalicVisible.triggered.connect(this, "toggleItalicVisible(Boolean)");\r
458                 underlineAction = buttonLayout.addWidget(underlineButton);\r
459                 buttonLayout.toggleUnderlineVisible.triggered.connect(this, "toggleUnderlineVisible(Boolean)");\r
460                 strikethroughAction = buttonLayout.addWidget(strikethroughButton);\r
461                 buttonLayout.toggleStrikethroughVisible.triggered.connect(this, "toggleStrikethroughVisible(Boolean)");\r
462 \r
463                 \r
464                 buttonLayout.addWidget(newSeparator());\r
465                 leftAlignAction = buttonLayout.addWidget(leftAlignButton);\r
466                 buttonLayout.toggleLeftAlignVisible.triggered.connect(this, "toggleLeftAlignVisible(Boolean)");\r
467                 centerAlignAction = buttonLayout.addWidget(centerAlignButton);\r
468                 buttonLayout.toggleCenterAlignVisible.triggered.connect(this, "toggleCenterAlignVisible(Boolean)");\r
469                 rightAlignAction = buttonLayout.addWidget(rightAlignButton);\r
470                 buttonLayout.toggleRightAlignVisible.triggered.connect(this, "toggleRightAlignVisible(Boolean)");\r
471 \r
472                 buttonLayout.addWidget(newSeparator());\r
473                 hlineAction = buttonLayout.addWidget(hlineButton);\r
474                 buttonLayout.toggleHLineVisible.triggered.connect(this, "toggleHLineVisible(Boolean)");\r
475 \r
476                 indentAction = buttonLayout.addWidget(indentButton);\r
477                 buttonLayout.toggleIndentVisible.triggered.connect(this, "toggleIndentVisible(Boolean)");\r
478                 outdentAction = buttonLayout.addWidget(outdentButton);\r
479                 buttonLayout.toggleOutdentVisible.triggered.connect(this, "toggleOutdentVisible(Boolean)");\r
480                 bulletListAction = buttonLayout.addWidget(bulletListButton);\r
481                 buttonLayout.toggleBulletListVisible.triggered.connect(this, "toggleBulletListVisible(Boolean)");\r
482                 numberListAction = buttonLayout.addWidget(numberListButton);\r
483                 buttonLayout.toggleNumberListVisible.triggered.connect(this, "toggleNumberListVisible(Boolean)");\r
484 \r
485                 // Setup the font & font size combo boxes\r
486                 buttonLayout.addWidget(newSeparator());\r
487                 fontList = new QComboBox();\r
488                 fontSize = new QComboBox();\r
489                 fontList.setToolTip("Font");\r
490                 fontSize.setToolTip("Font Size");\r
491                 fontList.activated.connect(this, "fontChanged(String)");\r
492                 fontSize.activated.connect(this, "fontSizeChanged(String)");\r
493                 fontListAction = buttonLayout.addWidget(fontList);\r
494                 buttonLayout.toggleFontVisible.triggered.connect(this, "toggleFontListVisible(Boolean)");\r
495                 fontSizeAction = buttonLayout.addWidget(fontSize);\r
496                 buttonLayout.toggleFontSizeVisible.triggered.connect(this, "toggleFontSizeVisible(Boolean)");\r
497                 QFontDatabase fonts = new QFontDatabase();\r
498                 List<String> fontFamilies = fonts.families();\r
499                 for (int i = 0; i < fontFamilies.size(); i++) {\r
500                         fontList.addItem(fontFamilies.get(i));\r
501                         if (i == 0) {\r
502                                 loadFontSize(fontFamilies.get(i));\r
503                         }\r
504                 }\r
505 \r
506 //              buttonLayout.addWidget(newSeparator(), 0);\r
507                 fontColor = newToolButton("fontColor", tr("Font Color"));\r
508                 fontColorMenu = new ColorMenu(this);\r
509                 fontColor.setMenu(fontColorMenu.getMenu());\r
510                 fontColor.setPopupMode(ToolButtonPopupMode.MenuButtonPopup);\r
511                 fontColor.setAutoRaise(false);\r
512                 fontColorMenu.getMenu().triggered.connect(this, "fontColorClicked()");\r
513                 fontColorAction = buttonLayout.addWidget(fontColor);\r
514                 buttonLayout.toggleFontColorVisible.triggered.connect(this, "toggleFontColorVisible(Boolean)");\r
515                 fontHilight = newToolButton("fontHilight", tr("Font Hilight Color"));\r
516                 fontHilight.setPopupMode(ToolButtonPopupMode.MenuButtonPopup);\r
517                 fontHilight.setAutoRaise(false);\r
518                 fontHilightColorMenu = new ColorMenu(this);\r
519                 fontHilightColorMenu.setDefault(QColor.yellow);\r
520                 fontHilight.setMenu(fontHilightColorMenu.getMenu());\r
521                 fontHilightColorMenu.getMenu().triggered.connect(this, "fontHilightClicked()");\r
522                 fontHilightAction = buttonLayout.addWidget(fontHilight);\r
523                 fontHilightColorMenu.setDefault(QColor.yellow);\r
524                 buttonLayout.toggleFontHilight.triggered.connect(this, "toggleFontHilightVisible(Boolean)");\r
525                 \r
526                 spellCheckAction = buttonLayout.addWidget(spellCheckButton);\r
527                 buttonLayout.toggleNumberListVisible.triggered.connect(this, "spellCheckClicked()");\r
528                 buttonLayout.toggleSpellCheck.triggered.connect(this, "toggleSpellCheckVisible(Boolean)");\r
529                 \r
530                 todoAction = buttonLayout.addWidget(todoButton);\r
531                 buttonLayout.toggleNumberListVisible.triggered.connect(this, "todoClicked()");\r
532                 buttonLayout.toggleTodo.triggered.connect(this, "toggleTodoVisible(Boolean)");\r
533 \r
534 \r
535 //              buttonLayout.addWidget(new QLabel(), 1);\r
536                 v.addWidget(browser, 1);\r
537                 setLayout(v);\r
538 \r
539                 browser.downloadAttachmentRequested.connect(this,\r
540                                 "downloadAttachment(QNetworkRequest)");\r
541                 browser.downloadImageRequested.connect(this,\r
542                                 "downloadImage(QNetworkRequest)");\r
543                 setTabOrder(notebookBox, tagEdit);\r
544                 setTabOrder(tagEdit, browser);\r
545                 \r
546                 focusNoteShortcut = new QShortcut(this);\r
547                 setupShortcut(focusNoteShortcut, "Focus_Note");\r
548                 focusNoteShortcut.activated.connect(this, "focusNote()");\r
549                 focusTitleShortcut = new QShortcut(this);\r
550                 setupShortcut(focusTitleShortcut, "Focus_Title");\r
551                 focusTitleShortcut.activated.connect(this, "focusTitle()");\r
552                 focusTagShortcut = new QShortcut(this);\r
553                 setupShortcut(focusTagShortcut, "Focus_Tag");\r
554                 focusTagShortcut.activated.connect(this, "focusTag()");\r
555                 focusAuthorShortcut = new QShortcut(this);\r
556                 setupShortcut(focusAuthorShortcut, "Focus_Author");\r
557                 focusAuthorShortcut.activated.connect(this, "focusAuthor()");\r
558                 focusUrlShortcut = new QShortcut(this);\r
559                 setupShortcut(focusUrlShortcut, "Focus_Url");\r
560                 focusUrlShortcut.activated.connect(this, "focusUrl()");\r
561                 \r
562                 browser.page().mainFrame().setTextSizeMultiplier(Global.getTextSizeMultiplier());\r
563                 browser.page().mainFrame().setZoomFactor(Global.getZoomFactor());\r
564                 \r
565                 previewPageList = new HashMap<String,Integer>();\r
566                 \r
567                 browser.page().microFocusChanged.connect(this, "microFocusChanged()");\r
568                 \r
569                 logger.log(logger.HIGH, "Browser setup complete");\r
570         }\r
571 \r
572         \r
573         \r
574         private void setupShortcut(QShortcut action, String text) {\r
575                 if (!Global.shortcutKeys.containsAction(text))\r
576                         return;\r
577                 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));\r
578         }\r
579         \r
580         \r
581 \r
582         \r
583         // Getter for the QWebView\r
584         public QWebView getBrowser() {\r
585                 return browser;\r
586         }\r
587 \r
588         // Block signals while loading data or things are flagged as dirty by\r
589         // mistake\r
590         public void loadingData(boolean val) {\r
591                 logger.log(logger.EXTREME, "Entering BrowserWindow.loadingData() " +val);\r
592                 notebookBox.blockSignals(val);\r
593                 browser.page().blockSignals(val);\r
594                 browser.page().mainFrame().blockSignals(val);\r
595                 titleLabel.blockSignals(val);\r
596                 alteredDate.blockSignals(val);\r
597                 alteredTime.blockSignals(val);\r
598                 createdTime.blockSignals(val);\r
599                 createdDate.blockSignals(val);\r
600                 subjectDate.blockSignals(val);\r
601                 subjectTime.blockSignals(val);\r
602                 urlText.blockSignals(val);\r
603                 authorText.blockSignals(val);\r
604                 if (!val)\r
605                         exposeToJavascript();\r
606                 logger.log(logger.EXTREME, "Exiting BrowserWindow.loadingData() " +val);\r
607         }\r
608 \r
609         // Enable/disable\r
610         public void setReadOnly(boolean v) {\r
611                 setEnabled(true);\r
612                 titleLabel.setEnabled(!v);\r
613                 notebookBox.setEnabled(!v);\r
614                 tagEdit.setEnabled(!v);\r
615                 authorLabel.setEnabled(!v);\r
616                 geoBox.setEnabled(!v);\r
617                 urlText.setEnabled(!v);\r
618                 createdDate.setEnabled(!v);\r
619                 subjectDate.setEnabled(!v);\r
620                 alteredDate.setEnabled(!v);\r
621                 getBrowser().setEnabled(true);\r
622         }\r
623         \r
624         // expose this class to Javascript on the web page\r
625         private void exposeToJavascript() {\r
626                 browser.page().mainFrame().addToJavaScriptWindowObject("jambi", this);\r
627         }\r
628 \r
629         // Custom event queue\r
630         @Override\r
631         public boolean event(QEvent e) {\r
632                 if (e.type().equals(QEvent.Type.FocusOut)) {\r
633                         logger.log(logger.EXTREME, "Focus lost");\r
634                         focusLost.emit();\r
635                 }\r
636                 return super.event(e);\r
637         }\r
638 \r
639         // clear out browser\r
640         public void clear() {\r
641                 logger.log(logger.EXTREME, "Entering BrowserWindow.clear()");\r
642                 setNote(null);\r
643                 browser.setContent(new QByteArray());\r
644                 tagEdit.setText("");\r
645                 tagEdit.tagCompleter.reset();\r
646                 urlLabel.setText(tr("Source URL:"));\r
647                 titleLabel.setText("");\r
648                 logger.log(logger.EXTREME, "Exiting BrowserWindow.clear()");\r
649         }\r
650 \r
651         // get/set current note\r
652         public void setNote(Note n) {\r
653                 currentNote = n;\r
654                 if (n == null)\r
655                         n = new Note();\r
656                 saveNoteTitle = n.getTitle();\r
657 \r
658         }\r
659 \r
660         public Note getNote() {\r
661                 return currentNote;\r
662         }\r
663 \r
664         // New Editor Button\r
665         private QPushButton newEditorButton(String name, String toolTip) {\r
666                 QPushButton button = new QPushButton();\r
667                 QIcon icon = new QIcon(iconPath + name + ".gif");\r
668                 button.setIcon(icon);\r
669                 button.setToolTip(toolTip);\r
670                 button.clicked.connect(this, name + "Clicked()");\r
671                 return button;\r
672         }\r
673         // New Editor Button\r
674         private QToolButton newToolButton(String name, String toolTip) {\r
675                 QToolButton button = new QToolButton();\r
676                 QIcon icon = new QIcon(iconPath + name + ".gif");\r
677                 button.setIcon(icon);\r
678                 button.setToolTip(toolTip);\r
679                 button.clicked.connect(this, name + "Clicked()");\r
680                 return button;\r
681         }\r
682 \r
683         // New Separator\r
684         private QLabel newSeparator() {\r
685                 return new QLabel("   ");\r
686         }\r
687 \r
688         // Set the title in the window\r
689         public void setTitle(String t) {\r
690                 titleLabel.setText(t);\r
691                 saveNoteTitle = t;\r
692                 checkNoteTitle();\r
693         }\r
694 \r
695         // Return the current text title\r
696         public String getTitle() {\r
697                 return titleLabel.text();\r
698         }\r
699 \r
700         // Set the tag name string\r
701         public void setTag(String t) {\r
702                 saveTagList = t;\r
703                 tagEdit.setText(t);\r
704                 tagEdit.tagCompleter.reset();\r
705         }\r
706 \r
707         // Set the source URL\r
708         public void setUrl(String t) {\r
709                 urlLabel.setText(tr("Source URL:\t"));\r
710                 urlText.setText(t);\r
711         }\r
712 \r
713         // The user want's to launch a web browser on the source of the URL\r
714         public void sourceUrlClicked() {\r
715                 // Make sure we have a valid URL\r
716                 if (urlText.text().trim().equals(""))\r
717                         return;\r
718                 \r
719                 String url = urlText.text();\r
720                 if (!url.toLowerCase().startsWith(tr("http://")))\r
721                         url = tr("http://") +url;\r
722                 \r
723         if (!QDesktopServices.openUrl(new QUrl(url))) {\r
724                 logger.log(logger.LOW, "Error opening file :" +url);\r
725         }\r
726         }\r
727         \r
728         public void setAuthor(String t) {\r
729                 authorLabel.setText(tr("Author:\t"));\r
730                 authorText.setText(t);\r
731         }\r
732 \r
733         // Set the creation date\r
734         public void setCreation(long date) {\r
735                 QDateTime dt = new QDateTime();\r
736                 dt.setTime_t((int) (date / 1000));\r
737                 createdDate.setDateTime(dt);\r
738                 createdTime.setDateTime(dt);\r
739                 createdDate.setDisplayFormat(Global.getDateFormat());\r
740                 createdTime.setDisplayFormat(Global.getTimeFormat());\r
741         }\r
742 \r
743         // Set the creation date\r
744         public void setAltered(long date) {\r
745                 QDateTime dt = new QDateTime();\r
746                 dt.setTime_t((int) (date / 1000));\r
747                 alteredDate.setDateTime(dt);\r
748                 alteredTime.setDateTime(dt);\r
749                 alteredDate.setDisplayFormat(Global.getDateFormat());\r
750                 alteredTime.setDisplayFormat(Global.getTimeFormat());\r
751         }\r
752 \r
753         // Set the subject date\r
754         public void setSubjectDate(long date) {\r
755                 QDateTime dt = new QDateTime();\r
756                 dt.setTime_t((int) (date / 1000));\r
757                 subjectDate.setDateTime(dt);\r
758                 subjectTime.setDateTime(dt);\r
759                 subjectDate.setDisplayFormat(Global.getDateFormat());\r
760                 subjectTime.setDisplayFormat(Global.getTimeFormat());\r
761         }\r
762 \r
763         // Toggle the extended attribute information\r
764         public void toggleInformation() {\r
765                 if (extendedOn) {\r
766                         extendedOn = false;\r
767                 } else {\r
768                         extendedOn = true;\r
769                 }\r
770                 urlLabel.setVisible(extendedOn);\r
771                 urlText.setVisible(extendedOn);\r
772                 authorText.setVisible(extendedOn);\r
773                 geoBox.setVisible(extendedOn);\r
774                 authorLabel.setVisible(extendedOn);\r
775                 createdDate.setVisible(extendedOn);\r
776                 createdTime.setVisible(extendedOn);\r
777                 createdLabel.setVisible(extendedOn);\r
778                 alteredLabel.setVisible(extendedOn);\r
779                 alteredDate.setVisible(extendedOn);\r
780                 alteredTime.setVisible(extendedOn);\r
781                 //notebookBox.setVisible(extendedOn);\r
782                 notebookLabel.setVisible(extendedOn);\r
783                 subjectLabel.setVisible(extendedOn);\r
784                 subjectDate.setVisible(extendedOn);\r
785                 subjectTime.setVisible(extendedOn);\r
786         }\r
787 \r
788         public void hideButtons() {\r
789 \r
790                 undoButton.parentWidget().setVisible(false);\r
791                 buttonsVisible = false;\r
792         }\r
793 \r
794 \r
795         // Is the extended view on?\r
796         public boolean isExtended() {\r
797                 return extendedOn;\r
798         }\r
799 \r
800         // Listener for when a link is clicked\r
801         @SuppressWarnings("unused")\r
802         private void openFile() {\r
803                 logger.log(logger.EXTREME, "Starting openFile()");\r
804                 File fileHandle = new File(selectedFile);\r
805                 URI fileURL = fileHandle.toURI();\r
806                 String localURL = fileURL.toString();\r
807                 QUrl url = new QUrl(localURL);\r
808                 QFile file = new QFile(selectedFile);\r
809                 \r
810                 logger.log(logger.EXTREME, "Adding to fileWatcher:"+file.fileName());\r
811                 fileWatcher.addPath(file.fileName());\r
812         \r
813         if (!QDesktopServices.openUrl(url)) {\r
814                 logger.log(logger.LOW, "Error opening file :" +url);\r
815         }\r
816         }\r
817         \r
818         \r
819         // Listener for when a link is clicked\r
820         @SuppressWarnings("unused")\r
821         private void linkClicked(QUrl url) {\r
822                 logger.log(logger.EXTREME, "URL Clicked: " +url.toString());\r
823                 if (url.toString().substring(0,8).equals("nnres://")) {\r
824                         logger.log(logger.EXTREME, "URL is NN resource");\r
825                         if (url.toString().endsWith("/vnd.evernote.ink")) {\r
826                                 logger.log(logger.EXTREME, "Unable to open ink note");\r
827                                 QMessageBox.information(this, tr("Unable Open"), tr("This is an ink note.\n"+\r
828                                         "Ink notes are not supported since Evernote has not\n published any specifications on them\n" +\r
829                                         "and I'm too lazy to figure them out by myself."));\r
830                                 return;\r
831                         }\r
832                         String fullName = url.toString().substring(8);\r
833                         int index = fullName.indexOf(".");\r
834                         String guid = "";\r
835                         String type = "";\r
836                         if (index >-1) {\r
837                                 type = fullName.substring(index+1);\r
838                                 guid = fullName.substring(0,index);\r
839                         }\r
840                         index = guid.indexOf(Global.attachmentNameDelimeter);\r
841                         if (index > -1) {\r
842                                 guid = guid.substring(0,index);\r
843                         }\r
844                         List<Resource> resList = currentNote.getResources();\r
845                         Resource res = null;\r
846                         for (int i=0; i<resList.size(); i++) {\r
847                                 if (resList.get(i).getGuid().equals(guid)) {\r
848                                         res = resList.get(i);\r
849                                         i=resList.size();\r
850                                 }\r
851                         }\r
852                         if (res == null) {\r
853                                 String resGuid = Global.resourceMap.get(guid);\r
854                                 if (resGuid != null) \r
855                                         res = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid, true);\r
856                         }\r
857                         if (res != null) {\r
858                                 String fileName;\r
859                                 if (res.getAttributes() != null && \r
860                                                 res.getAttributes().getFileName() != null && \r
861                                                 !res.getAttributes().getFileName().trim().equals(""))\r
862                                         fileName = res.getGuid()+Global.attachmentNameDelimeter+res.getAttributes().getFileName();\r
863                                 else\r
864                                         fileName = res.getGuid()+"."+type;\r
865                                 QFile file = new QFile(Global.getFileManager().getResDirPath(fileName));\r
866                         QFile.OpenMode mode = new QFile.OpenMode();\r
867                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
868                         boolean openResult = file.open(mode);\r
869                                 logger.log(logger.EXTREME, "File opened:" +openResult);\r
870                         QDataStream out = new QDataStream(file);\r
871                         Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(res.getGuid(), true);\r
872                                 QByteArray binData = new QByteArray(resBinary.getData().getBody());\r
873                                 resBinary = null;\r
874                                 logger.log(logger.EXTREME, "Writing resource");\r
875                         out.writeBytes(binData.toByteArray());\r
876                         file.close();\r
877                                 \r
878                         String whichOS = System.getProperty("os.name");\r
879                                 if (whichOS.contains("Windows")) \r
880                                 url.setUrl("file:///"+file.fileName());\r
881                         else\r
882                                 url.setUrl("file://"+file.fileName());\r
883                  //       fileWatcher.removePath(file.fileName());\r
884                                 logger.log(logger.EXTREME, "Adding file watcher " +file.fileName());\r
885                                 fileWatcher.addPath(file.fileName());\r
886                         \r
887                         // If we can't open it, then prompt the user to save it.\r
888                         if (!QDesktopServices.openUrl(url)) {\r
889                                         logger.log(logger.EXTREME, "We can't handle this.  Where do we put it?");\r
890                                 QFileDialog dialog = new QFileDialog();\r
891                                 dialog.show();\r
892                                 if (dialog.exec()!=0) {\r
893                                         List<String> fileNames = dialog.selectedFiles(); //gets all selected filenames\r
894                                         if (fileNames.size() == 0) \r
895                                                 return;\r
896                                         String sf = fileNames.get(0);\r
897                                         QFile saveFile = new QFile(sf);\r
898                                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
899                                         saveFile.open(mode);\r
900                                         QDataStream saveOut = new QDataStream(saveFile);\r
901                                         saveOut.writeBytes(binData.toByteArray());\r
902                                         saveFile.close();\r
903                                         return;\r
904                                 }\r
905                                 }\r
906                         }\r
907                         return;\r
908                 }\r
909                 logger.log(logger.EXTREME, "Launching URL");\r
910                 QDesktopServices.openUrl(url);\r
911         }\r
912 \r
913         // Listener for when BOLD is clicked\r
914         @SuppressWarnings("unused")\r
915         private void undoClicked() {\r
916                 browser.page().triggerAction(WebAction.Undo);\r
917                 browser.setFocus();\r
918         }\r
919 \r
920         // Listener for when BOLD is clicked\r
921         @SuppressWarnings("unused")\r
922         private void redoClicked() {\r
923                 browser.page().triggerAction(WebAction.Redo);\r
924                 browser.setFocus();\r
925         }\r
926 \r
927         // Listener for when BOLD is clicked\r
928         @SuppressWarnings("unused")\r
929         private void boldClicked() {\r
930                 browser.page().triggerAction(WebAction.ToggleBold);\r
931                 microFocusChanged();\r
932                 browser.setFocus();\r
933         }\r
934 \r
935         // Listener for when Italics is clicked\r
936         @SuppressWarnings("unused")\r
937         private void italicClicked() {\r
938                 browser.page().triggerAction(WebAction.ToggleItalic);\r
939                 microFocusChanged();\r
940                 browser.setFocus();\r
941         }\r
942 \r
943         // Listener for when UNDERLINE is clicked\r
944         @SuppressWarnings("unused")\r
945         private void underlineClicked() {\r
946                 browser.page().triggerAction(WebAction.ToggleUnderline);\r
947                 microFocusChanged();\r
948                 browser.setFocus();\r
949         }\r
950 \r
951         // Listener for when Strikethrough is clicked\r
952         @SuppressWarnings("unused")\r
953         private void strikethroughClicked() {\r
954                 browser.page().mainFrame().evaluateJavaScript(\r
955                                 "document.execCommand('strikeThrough', false, '');");\r
956                 browser.setFocus();\r
957         }\r
958 \r
959         // Listener for when cut is clicked\r
960         @SuppressWarnings("unused")\r
961         private void cutClicked() {\r
962                 browser.page().triggerAction(WebAction.Cut);\r
963                 browser.setFocus();\r
964         }\r
965 \r
966         // Listener when COPY is clicked\r
967         @SuppressWarnings("unused")\r
968         private void copyClicked() {\r
969                 browser.page().triggerAction(WebAction.Copy);\r
970                 browser.setFocus();\r
971         }\r
972 \r
973         // Listener when PASTE is clicked\r
974         public void pasteClicked() {\r
975                 logger.log(logger.EXTREME, "Paste Clicked");\r
976                 if (forceTextPaste) {\r
977                         pasteWithoutFormattingClicked();\r
978                         return;\r
979                 }\r
980                 QClipboard clipboard = QApplication.clipboard();\r
981                 QMimeData mime = clipboard.mimeData();\r
982                 \r
983 //               String x = mime.html();\r
984 \r
985                 if (mime.hasImage()) {\r
986                         logger.log(logger.EXTREME, "Image paste found");\r
987                         insertImage(mime);\r
988                         browser.setFocus();\r
989                         return;\r
990                 }\r
991 \r
992                 if (mime.hasUrls()) {\r
993                         logger.log(logger.EXTREME, "URL paste found");\r
994                         handleUrls(mime);\r
995                         browser.setFocus();\r
996                         return;\r
997                 }\r
998                 \r
999                 String text = mime.html();\r
1000                 if (text.contains("en-tag") && mime.hasHtml()) {\r
1001                         logger.log(logger.EXTREME, "Intra-note paste found");\r
1002                         text = fixInternotePaste(text);\r
1003                         mime.setHtml(text);\r
1004                         clipboard.setMimeData(mime);\r
1005                 }\r
1006 \r
1007                 logger.log(logger.EXTREME, "Final paste choice encountered");\r
1008                 browser.page().triggerAction(WebAction.Paste);\r
1009                 browser.setFocus();\r
1010 \r
1011         }\r
1012 \r
1013         // Paste text without formatting\r
1014         private void pasteWithoutFormattingClicked() {\r
1015                 logger.log(logger.EXTREME, "Paste without format clipped");\r
1016                 QClipboard clipboard = QApplication.clipboard();\r
1017                 QMimeData mime = clipboard.mimeData();\r
1018                 if (!mime.hasText())\r
1019                         return;\r
1020                 String text = mime.text();\r
1021                 clipboard.setText(text);\r
1022                 browser.page().triggerAction(WebAction.Paste);\r
1023                 QApplication.clipboard().setMimeData(mime);\r
1024                 browser.setFocus();\r
1025 \r
1026         }\r
1027         \r
1028         // insert date/time\r
1029         @SuppressWarnings("unused")\r
1030         private void insertDateTime() {\r
1031                 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();\r
1032                 String dateTimeFormat = new String(fmt);\r
1033                 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);\r
1034                 Calendar cal = Calendar.getInstance();\r
1035                 \r
1036                 browser.page().mainFrame().evaluateJavaScript(\r
1037                         "document.execCommand('insertHtml', false, '"+simple.format(cal.getTime())+"');");\r
1038                 \r
1039                 browser.setFocus();\r
1040 \r
1041         }\r
1042 \r
1043         // Listener when Left is clicked\r
1044         @SuppressWarnings("unused")\r
1045         private void justifyLeftClicked() {\r
1046                 browser.page().mainFrame().evaluateJavaScript(\r
1047                                 "document.execCommand('JustifyLeft', false, '');");\r
1048                 browser.setFocus();\r
1049         }\r
1050 \r
1051         // Listener when Center is clicked\r
1052         @SuppressWarnings("unused")\r
1053         private void justifyCenterClicked() {\r
1054                 browser.page().mainFrame().evaluateJavaScript(\r
1055                                 "document.execCommand('JustifyCenter', false, '');");\r
1056                 browser.setFocus();\r
1057         }\r
1058 \r
1059         // Listener when Left is clicked\r
1060         @SuppressWarnings("unused")\r
1061         private void justifyRightClicked() {\r
1062                 browser.page().mainFrame().evaluateJavaScript(\r
1063                                 "document.execCommand('JustifyRight', false, '');");\r
1064                 browser.setFocus();\r
1065         }\r
1066 \r
1067         // Listener when HLINE is clicked\r
1068         @SuppressWarnings("unused")\r
1069         private void hlineClicked() {\r
1070                 browser.page().mainFrame().evaluateJavaScript(\r
1071                                 "document.execCommand('insertHorizontalRule', false, '');");\r
1072                 browser.setFocus();\r
1073         }\r
1074 \r
1075         // Listener when outdent is clicked\r
1076         private void outdentClicked() {\r
1077                 browser.page().mainFrame().evaluateJavaScript(\r
1078                                 "document.execCommand('outdent', false, '');");\r
1079                 browser.setFocus();\r
1080         }\r
1081 \r
1082         // Listener when a bullet list is clicked\r
1083         @SuppressWarnings("unused")\r
1084         private void bulletListClicked() {\r
1085                 browser.page().mainFrame().evaluateJavaScript(\r
1086                                 "document.execCommand('InsertUnorderedList', false, '');");\r
1087                 browser.setFocus();\r
1088         }\r
1089 \r
1090         // Listener when a bullet list is clicked\r
1091         @SuppressWarnings("unused")\r
1092         private void numberListClicked() {\r
1093                 browser.page().mainFrame().evaluateJavaScript(\r
1094                                 "document.execCommand('InsertOrderedList', false, '');");\r
1095                 browser.setFocus();\r
1096         }\r
1097 \r
1098         // Listener when indent is clicked\r
1099         private void indentClicked() {\r
1100                 browser.page().mainFrame().evaluateJavaScript(\r
1101                                 "document.execCommand('indent', false, '');");\r
1102                 browser.setFocus();\r
1103         }\r
1104 \r
1105         // Listener when the font name is changed\r
1106         @SuppressWarnings("unused")\r
1107         private void fontChanged(String font) {\r
1108                 browser.page().mainFrame().evaluateJavaScript(\r
1109                                 "document.execCommand('fontName',false,'" + font + "');");\r
1110                 browser.setFocus();\r
1111         }\r
1112 \r
1113         // Listener when a font size is changed\r
1114         @SuppressWarnings("unused")\r
1115         private void fontSizeChanged(String font) {\r
1116                 String text = browser.selectedText();\r
1117                 if (text.trim().equalsIgnoreCase(""))\r
1118                         return;\r
1119 \r
1120                 String selectedText = browser.selectedText();\r
1121                 String url = "<span style=\"font-size:" +font +"pt; \">"+selectedText +"</a>";\r
1122                 String script = "document.execCommand('insertHtml', false, '"+url+"');";\r
1123                 browser.page().mainFrame().evaluateJavaScript(script);\r
1124 /*              browser.page().mainFrame().evaluateJavaScript(\r
1125                                 "document.execCommand('fontSize',false,'"\r
1126                                                 + font + "');");\r
1127 */\r
1128                 browser.setFocus();\r
1129         }\r
1130 \r
1131         // Load the font combo box based upon the font selected\r
1132         private void loadFontSize(String name) {        \r
1133                 QFontDatabase db = new QFontDatabase(); \r
1134                 fontSize.clear();\r
1135                 List<Integer> points = db.pointSizes(name); \r
1136                 for (int i=0; i<points.size(); i++) { \r
1137                         fontSize.addItem(points.get(i).toString()); \r
1138                 }\r
1139                 /*\r
1140                 fontSize.addItem("x-small");\r
1141                 fontSize.addItem("small");\r
1142                 fontSize.addItem("medium");\r
1143                 fontSize.addItem("large");\r
1144                 fontSize.addItem("x-large");\r
1145                 fontSize.addItem("xx-large");\r
1146                 fontSize.addItem("xxx-large");\r
1147                 */\r
1148         }\r
1149 \r
1150         // Listener when a font size is changed\r
1151         @SuppressWarnings("unused")\r
1152         private void fontColorClicked() {\r
1153 //              QColorDialog dialog = new QColorDialog();\r
1154 //              QColor color = QColorDialog.getColor();\r
1155                 QColor color = fontColorMenu.getColor();\r
1156                 if (color.isValid())\r
1157                         browser.page().mainFrame().evaluateJavaScript(\r
1158                                         "document.execCommand('foreColor',false,'" + color.name()\r
1159                                                         + "');");\r
1160                 browser.setFocus();\r
1161         }\r
1162 \r
1163         // Listener for when a background color change is requested\r
1164         @SuppressWarnings("unused")\r
1165         private void fontHilightClicked() {\r
1166 //              QColorDialog dialog = new QColorDialog();\r
1167 //              QColor color = QColorDialog.getColor();\r
1168                 QColor color = fontHilightColorMenu.getColor();\r
1169                 if (color.isValid())\r
1170                         browser.page().mainFrame().evaluateJavaScript(\r
1171                                         "document.execCommand('backColor',false,'" + color.name()\r
1172                                                         + "');");\r
1173                 browser.setFocus();\r
1174         }\r
1175         \r
1176         // Listener for when a background color change is requested\r
1177         @SuppressWarnings("unused")\r
1178         private void superscriptClicked() {\r
1179                 browser.page().mainFrame().evaluateJavaScript(\r
1180                                         "document.execCommand('superscript');");\r
1181                 browser.setFocus();\r
1182         }\r
1183         \r
1184         // Listener for when a background color change is requested\r
1185         @SuppressWarnings("unused")\r
1186         private void subscriptClicked() {\r
1187                 browser.page().mainFrame().evaluateJavaScript(\r
1188                                         "document.execCommand('subscript');");\r
1189                 browser.setFocus();\r
1190         }\r
1191         // Insert a to-do checkbox\r
1192         @SuppressWarnings("unused")\r
1193         private void todoClicked() {\r
1194                 FileNameMap fileNameMap = URLConnection.getFileNameMap();\r
1195                 String script_start = new String(\r
1196                                 "document.execCommand('insertHtml', false, '");\r
1197                 String script_end = new String("');");\r
1198                 String todo = new String(\r
1199                                 "<input TYPE=\"CHECKBOX\" value=\"false\" onClick=\"value=checked; window.jambi.contentChanged(); \" />");\r
1200                 browser.page().mainFrame().evaluateJavaScript(\r
1201                                 script_start + todo + script_end);\r
1202                 browser.setFocus();\r
1203         }\r
1204 \r
1205         // Encrypt the selected text\r
1206         @SuppressWarnings("unused")\r
1207         private void encryptText() {\r
1208                 String text = browser.selectedText();\r
1209                 if (text.trim().equalsIgnoreCase(""))\r
1210                         return;\r
1211 \r
1212                 EnCryptDialog dialog = new EnCryptDialog();\r
1213                 dialog.exec();\r
1214                 if (!dialog.okPressed()) {\r
1215                         return;\r
1216                 }\r
1217 \r
1218                 EnCrypt crypt = new EnCrypt();\r
1219                 String encrypted = crypt.encrypt(text, dialog.getPassword().trim(), 64);\r
1220 \r
1221                 if (encrypted.trim().equals("")) {\r
1222                         QMessageBox.information(this, tr("Error"), tr("Error Encrypting String"));\r
1223                         return;\r
1224                 }\r
1225                 StringBuffer buffer = new StringBuffer(encrypted.length() + 100);\r
1226                 buffer.append("<img en-tag=\"en-crypt\" cipher=\"RC2\" hint=\""\r
1227                                 + dialog.getHint().replace("'","\\'") + "\" length=\"64\" ");\r
1228                 buffer.append("contentEditable=\"false\" alt=\"");\r
1229                 buffer.append(encrypted);\r
1230                 // NFC FIXME: should this be a file URL like in handleLocalAttachment and importAttachment?\r
1231                 buffer.append("\" src=\"").append(FileUtils.toForwardSlashedPath(Global.getFileManager().getImageDirPath("encrypt.png") +"\""));\r
1232                 Global.cryptCounter++;\r
1233                 buffer.append(" id=\"crypt"+Global.cryptCounter.toString() +"\"");\r
1234                 buffer.append(" onMouseOver=\"style.cursor=\\'hand\\'\"");\r
1235                 buffer.append(" onClick=\"window.jambi.decryptText(\\'crypt"+Global.cryptCounter.toString() \r
1236                                 +"\\', \\'"+encrypted+"\\', \\'"+dialog.getHint().replace("'", "\\&amp;apos;")+"\\');\"");\r
1237                 buffer.append("style=\"display:block\" />");\r
1238 \r
1239                 String script_start = new String(\r
1240                                 "document.execCommand('insertHtml', false, '");\r
1241                 String script_end = new String("');");\r
1242                 browser.page().mainFrame().evaluateJavaScript(\r
1243                                 script_start + buffer.toString() + script_end);\r
1244         }\r
1245 \r
1246         \r
1247         // Insert a hyperlink\r
1248         public void insertLink() {\r
1249                 logger.log(logger.EXTREME, "Inserting link");\r
1250                 String text = browser.selectedText();\r
1251                 if (text.trim().equalsIgnoreCase(""))\r
1252                         return;\r
1253 \r
1254                 InsertLinkDialog dialog = new InsertLinkDialog();\r
1255                 if (currentHyperlink != null && currentHyperlink != "") {\r
1256                         dialog.setUrl(currentHyperlink);\r
1257                 }\r
1258                 dialog.exec();\r
1259                 if (!dialog.okPressed()) {\r
1260                         logger.log(logger.EXTREME, "Insert link canceled");\r
1261                         return;\r
1262                 }\r
1263                 if (browser.insertLinkAction.text().equalsIgnoreCase("Insert Hyperlink")) {\r
1264                         String selectedText = browser.selectedText();\r
1265                         logger.log(logger.EXTREME, "Inserting link on text "+selectedText);\r
1266                         logger.log(logger.EXTREME, "URL Link " +dialog.getUrl().trim());\r
1267                         String dUrl = StringUtils.replace(dialog.getUrl().trim(), "'", "\\'");\r
1268                         String url = "<a href=\"" +dUrl\r
1269                                         +"\" title=" +dUrl \r
1270                                         +" >"+selectedText +"</a>";\r
1271                         String script = "document.execCommand('insertHtml', false, '"+url+"');";\r
1272                         browser.page().mainFrame().evaluateJavaScript(script);\r
1273                         return;\r
1274                 } else {\r
1275                         String js = new String( "function getCursorPos() {"\r
1276                                         +"var cursorPos;"\r
1277                                         +"if (window.getSelection) {"\r
1278                                         +"   var selObj = window.getSelection();"\r
1279                                         +"   var selRange = selObj.getRangeAt(0);"\r
1280                                         +"   var workingNode = window.getSelection().anchorNode.parentNode;"\r
1281                                         +"   while(workingNode != null) { " \r
1282                                         +"      if (workingNode.nodeName.toLowerCase()=='a') workingNode.setAttribute('href','" +dialog.getUrl() +"');"\r
1283                                         +"      workingNode = workingNode.parentNode;"\r
1284                                         +"   }"\r
1285                                         +"}"\r
1286                                         +"} getCursorPos();");\r
1287                                 browser.page().mainFrame().evaluateJavaScript(js);\r
1288                                 contentChanged();\r
1289                 }\r
1290                 \r
1291         }\r
1292         \r
1293         // Insert a table\r
1294         public void insertTable() {\r
1295                 TableDialog dialog = new TableDialog();\r
1296                 dialog.exec();\r
1297                 if (!dialog.okPressed()) {\r
1298                         return;\r
1299                 }\r
1300                 \r
1301                 int cols = dialog.getCols();\r
1302                 int rows = dialog.getRows();\r
1303                 int width = dialog.getWidth();\r
1304                 boolean percent = dialog.isPercent();\r
1305                 \r
1306                 String newHTML = "<table border=\"1\" width=\"" +new Integer(width).toString();\r
1307                 if (percent)\r
1308                         newHTML = newHTML +"%";\r
1309                 newHTML = newHTML + "\"><tbody>";\r
1310 \r
1311                 for (int i=0; i<rows; i++) {\r
1312                         newHTML = newHTML +"<tr>";\r
1313                         for (int j=0; j<cols; j++) {\r
1314                                 newHTML = newHTML +"<td>&nbsp;</td>";\r
1315                         }\r
1316                         newHTML = newHTML +"</tr>";\r
1317                 }\r
1318                 newHTML = newHTML+"</tbody></table>";   \r
1319         \r
1320                 String script = "document.execCommand('insertHtml', false, '"+newHTML+"');";\r
1321                 browser.page().mainFrame().evaluateJavaScript(script);\r
1322         }\r
1323         \r
1324         \r
1325         // Text content changed\r
1326         @SuppressWarnings("unused")\r
1327         private void selectionChanged() {\r
1328                 browser.encryptAction.setEnabled(true);\r
1329                 browser.insertLinkAction.setEnabled(true);\r
1330                 String scriptStart = "var selection_text = (window.getSelection()).toString();"\r
1331                                 + "var range = (window.getSelection()).getRangeAt(0);"\r
1332                                 + "var parent_html = range.commonAncestorContainer.innerHTML;"\r
1333                                 + "if (parent_html == undefined) {window.jambi.saveSelectedText(selection_text); return;}"\r
1334                                 + "var first_text = range.startContainer.nodeValue.substr(range.startOffset);"\r
1335                                 + "var last_text = (range.endContainer.nodeValue).substring(0,range.endOffset);"\r
1336                                 + "var start = parent_html.indexOf(first_text);"\r
1337                                 + "var end = parent_html.indexOf(last_text,start+1)+last_text.length;"\r
1338                                 + "var value = parent_html.substring(start,end);"\r
1339                                 + "window.jambi.saveSelectedText(value);" ;\r
1340                 browser.page().mainFrame().evaluateJavaScript(scriptStart);\r
1341 \r
1342         }\r
1343 \r
1344         public void saveSelectedText(String text) {\r
1345                 boolean enabled = true;\r
1346                 if (text.trim().length() == 0)\r
1347                         enabled=false;\r
1348                 if (text.indexOf("en-tag=\"en-crypt\"") >= 0)\r
1349                         enabled=false;\r
1350                 if (text.indexOf("<img en-tag=\"en-media\"") >= 0)\r
1351                         enabled=false;\r
1352                 if (text.indexOf("<a en-tag=\"en-media\"") >= 0)\r
1353                         enabled=false;\r
1354                 if (text.indexOf("<input ") >= 0)\r
1355                         enabled=false;\r
1356                 \r
1357                 browser.encryptAction.setEnabled(enabled);\r
1358                 browser.insertLinkAction.setEnabled(enabled);\r
1359 //              selectedText = text;\r
1360         }\r
1361 \r
1362         // Decrypt clicked text\r
1363         public void decryptText(String id, String text, String hint) {\r
1364                 EnCrypt crypt = new EnCrypt();\r
1365                 String plainText = null;\r
1366                 Calendar currentTime = new GregorianCalendar();\r
1367                 Long l = new Long(currentTime.getTimeInMillis());\r
1368                 String slot = new String(Long.toString(l));\r
1369                 \r
1370                 // First, try to decrypt with any keys we already have\r
1371                 for (int i=0; i<Global.passwordRemember.size(); i++) {\r
1372                         plainText = crypt.decrypt(text, Global.passwordRemember.get(i), 64);\r
1373                         if (plainText != null) {\r
1374                                 slot = new String(Long.toString(l));\r
1375                                 Global.passwordSafe.put(slot, Global.passwordRemember.get(i));\r
1376                                 removeEncryption(id, plainText, false, slot);   \r
1377                                 return;\r
1378                         }\r
1379                 }\r
1380                 \r
1381                 \r
1382                 EnDecryptDialog dialog = new EnDecryptDialog();\r
1383                 dialog.setHint(hint);\r
1384                 while (plainText == null || !dialog.okPressed()) {\r
1385                         dialog.exec();\r
1386                         if (!dialog.okPressed()) {\r
1387                                 return;\r
1388                         }\r
1389                         plainText = crypt.decrypt(text, dialog.getPassword().trim(), 64);\r
1390                         if (plainText == null) {\r
1391                                 QMessageBox.warning(this, "Incorrect Password", "The password entered is not correct");\r
1392                         }\r
1393                 }\r
1394                 Global.passwordSafe.put(slot, dialog.getPassword());\r
1395                 removeEncryption(id, plainText, dialog.permanentlyDecrypt(), slot);\r
1396                 if (dialog.rememberPassword())\r
1397                         Global.passwordRemember.add(dialog.getPassword());\r
1398 \r
1399         }\r
1400 \r
1401         // Get the editor tag line\r
1402         public TagLineEdit getTagLine() {\r
1403                 return tagEdit;\r
1404         }\r
1405 \r
1406         // Modify a note's tags\r
1407         @SuppressWarnings("unused")\r
1408         private void modifyTags() {\r
1409                 TagAssign tagWindow = new TagAssign(allTags, currentTags);\r
1410                 tagWindow.exec();\r
1411                 if (tagWindow.okClicked()) {\r
1412                         currentTags.clear();\r
1413                         StringBuffer tagDisplay = new StringBuffer();\r
1414 \r
1415                         List<QListWidgetItem> newTags = tagWindow.getTagList()\r
1416                                         .selectedItems();\r
1417                         for (int i = 0; i < newTags.size(); i++) {\r
1418                                 currentTags.add(newTags.get(i).text());\r
1419                                 tagDisplay.append(newTags.get(i).text());\r
1420                                 if (i < newTags.size() - 1) {\r
1421                                         tagDisplay.append(Global.tagDelimeter + " ");\r
1422                                 }\r
1423                         }\r
1424                         tagEdit.setText(tagDisplay.toString());\r
1425                         noteSignal.tagsChanged.emit(currentNote.getGuid(), currentTags);\r
1426                 }\r
1427         }\r
1428 \r
1429         // Tag line has been modified by typing text\r
1430         @SuppressWarnings("unused")\r
1431         private void modifyTagsTyping() {\r
1432                 String completionText = "";\r
1433                 if (tagEdit.currentCompleterSelection != null && !tagEdit.currentCompleterSelection.equals("")) {\r
1434                         completionText = tagEdit.currentCompleterSelection;\r
1435                         tagEdit.currentCompleterSelection = "";\r
1436                 }\r
1437                 \r
1438                 if (tagEdit.text().equalsIgnoreCase(saveTagList))\r
1439                         return;\r
1440 \r
1441                 // We know something has changed...\r
1442                 String oldTagArray[] = saveTagList.split(Global.tagDelimeter);\r
1443                 String newTagArray[];\r
1444                 if (!completionText.equals("")) {\r
1445                         String before = tagEdit.text().substring(0,tagEdit.cursorPosition());\r
1446                         before = before.substring(0,before.lastIndexOf(Global.tagDelimeter));\r
1447                         String after = tagEdit.text().substring(tagEdit.cursorPosition());\r
1448                         newTagArray = (before+Global.tagDelimeter+completionText+Global.tagDelimeter+after).split(Global.tagDelimeter);\r
1449                 }\r
1450                 else {\r
1451                         newTagArray = tagEdit.text().split(Global.tagDelimeter);\r
1452                 }\r
1453                 \r
1454                 // Remove any traling or leading blanks\r
1455                 for (int i=0; i<newTagArray.length; i++)\r
1456                         newTagArray[i] = newTagArray[i].trim().replaceAll("^\\s+", "");;\r
1457                 \r
1458                 // Remove any potential duplicates from the new list\r
1459                 for (int i=0; i<newTagArray.length; i++) {\r
1460                         boolean foundOnce = false;\r
1461                         for (int j=0; j<newTagArray.length; j++) {\r
1462                                 if (newTagArray[j].equalsIgnoreCase(newTagArray[i])) {\r
1463                                         if (!foundOnce) {\r
1464                                                 foundOnce = true;\r
1465                                         } else\r
1466                                                 newTagArray[j] = "";\r
1467                                 }\r
1468                         }\r
1469                 }\r
1470 \r
1471                 List<String> newTagList = new ArrayList<String>();\r
1472                 List<String> oldTagList = new ArrayList<String>();\r
1473 \r
1474                 for (int i = 0; i < oldTagArray.length; i++)\r
1475                         if (!oldTagArray[i].trim().equals(""))\r
1476                                 oldTagList.add(oldTagArray[i]);\r
1477                 for (int i = 0; i < newTagArray.length; i++)\r
1478                         if (!newTagArray[i].trim().equals(""))\r
1479                                 newTagList.add(newTagArray[i]);\r
1480 \r
1481                 // Let's cleanup the appearance of the tag list\r
1482                 Collections.sort(newTagList);\r
1483                 String newDisplay = "";\r
1484                 for (int i=0; i<newTagList.size(); i++) {\r
1485                         newDisplay = newDisplay+newTagList.get(i);\r
1486                         if (i<newTagList.size()-1)\r
1487                                 newDisplay = newDisplay+Global.tagDelimeter +" ";\r
1488                 }\r
1489                 tagEdit.blockSignals(true);\r
1490                 tagEdit.setText(newDisplay);\r
1491                 tagEdit.blockSignals(false);\r
1492                 \r
1493                 // We now have lists of the new & old. Remove duplicates. If all\r
1494                 // are removed from both then nothing has really changed\r
1495                 for (int i = newTagList.size() - 1; i >= 0; i--) {\r
1496                         String nTag = newTagList.get(i);\r
1497                         for (int j = oldTagList.size() - 1; j >= 0; j--) {\r
1498                                 String oTag = oldTagList.get(j);\r
1499                                 if (oTag.equalsIgnoreCase(nTag)) {\r
1500                                         oldTagList.remove(j);\r
1501                                         newTagList.remove(i);\r
1502                                         j = -1;\r
1503                                 }\r
1504                         }\r
1505                 }\r
1506 \r
1507                 if (oldTagList.size() != 0 || newTagList.size() != 0) {\r
1508                         currentTags.clear();\r
1509                         newTagArray = tagEdit.text().split(Global.tagDelimeter);\r
1510                         for (int i = 0; i < newTagArray.length; i++)\r
1511                                 if (!newTagArray[i].trim().equals(""))\r
1512                                         currentTags.add(newTagArray[i].trim());\r
1513 \r
1514                         noteSignal.tagsChanged.emit(currentNote.getGuid(), currentTags);\r
1515                 }\r
1516                 \r
1517         }\r
1518 \r
1519         // Tab button was pressed\r
1520         public void tabPressed() {\r
1521                 if (!insideList) {\r
1522                         String script_start = new String(\r
1523                         "document.execCommand('insertHtml', false, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');");\r
1524                         browser.page().mainFrame().evaluateJavaScript(script_start);\r
1525                 } else \r
1526                         indentClicked();\r
1527         }\r
1528         \r
1529         public void backtabPressed() {\r
1530                 if (insideList)\r
1531                         outdentClicked();\r
1532         }\r
1533         \r
1534         public void setInsideList() {\r
1535                 insideList = true;\r
1536         }\r
1537         \r
1538         // The title has been edited\r
1539         @SuppressWarnings("unused")\r
1540         private void titleEdited() {\r
1541                 // If we don't have a good note, or if the current title\r
1542                 // matches the old title then we don't need to do anything\r
1543                 if (currentNote == null)\r
1544                         return;\r
1545                 if (currentNote.getTitle().trim().equals(titleLabel.text().trim()))\r
1546                         return;\r
1547                 \r
1548                 // If we have a real change, we need to save it.\r
1549                 noteSignal.titleChanged.emit(currentNote.getGuid(), titleLabel.text());\r
1550                 currentNote.setTitle(titleLabel.text());\r
1551                 saveNoteTitle = titleLabel.text();\r
1552                 checkNoteTitle();\r
1553         }\r
1554 \r
1555         // Set the list of note tags\r
1556         public void setAllTags(List<Tag> l) {\r
1557                 allTags = l;\r
1558                 tagEdit.setTagList(l);\r
1559         }\r
1560 \r
1561         // Setter for the current tags\r
1562         public void setCurrentTags(List<String> s) {\r
1563                 currentTags = s;\r
1564         }\r
1565 \r
1566         // Save the list of notebooks\r
1567         public void setNotebookList(List<Notebook> n) {\r
1568                 notebookList = n;\r
1569                 loadNotebookList();\r
1570         }\r
1571 \r
1572         // Load the notebook list and select the current notebook\r
1573         private void loadNotebookList() {\r
1574                 if (notebookBox.count() != 0)\r
1575                         notebookBox.clear();\r
1576                 if (notebookList == null)\r
1577                         return;\r
1578 \r
1579                 for (int i = 0; i < notebookList.size(); i++) {\r
1580                         notebookBox.addItem(notebookList.get(i).getName());\r
1581                         if (currentNote != null) {\r
1582                                 if (currentNote.getNotebookGuid().equals(\r
1583                                                 notebookList.get(i).getGuid())) {\r
1584                                         notebookBox.setCurrentIndex(i);\r
1585                                 }\r
1586                         }\r
1587                 }\r
1588         }\r
1589 \r
1590         // Get the contents of the editor\r
1591         public String getContent() {\r
1592                 return browser.page().currentFrame().toHtml();\r
1593         }\r
1594 \r
1595         // The note contents have changed\r
1596         public void contentChanged() {\r
1597                 String content = getContent();\r
1598                 checkNoteTitle();\r
1599                 noteSignal.noteChanged.emit(currentNote.getGuid(), content); \r
1600         }\r
1601 \r
1602         // The notebook selection has changed\r
1603         @SuppressWarnings("unused")\r
1604         private void notebookChanged() {\r
1605                 boolean changed = false;\r
1606                 String n = notebookBox.currentText();\r
1607                 for (int i = 0; i < notebookList.size(); i++) {\r
1608                         if (n.equals(notebookList.get(i).getName())) {\r
1609                                 if (!notebookList.get(i).getGuid().equals(currentNote.getNotebookGuid())) {\r
1610                                         currentNote.setNotebookGuid(notebookList.get(i).getGuid());\r
1611                                         changed = true;\r
1612                                 }\r
1613                                 i = notebookList.size();\r
1614                         }\r
1615                 }\r
1616                 \r
1617                 // If the notebook changed, signal the update\r
1618                 if (changed)\r
1619                         noteSignal.notebookChanged.emit(currentNote.getGuid(), currentNote\r
1620                                         .getNotebookGuid());\r
1621         }\r
1622 \r
1623         // Check the note title\r
1624         private void checkNoteTitle() {\r
1625                 String text = browser.page().currentFrame().toPlainText();\r
1626                 if (saveNoteTitle.trim().equals("") || saveNoteTitle.trim().equals("Untitled Note")) {\r
1627                         int newLine = text.indexOf("\n");\r
1628                         if (newLine > 0) {\r
1629                                 text = text.substring(0, newLine);\r
1630                                 if (text.trim().equals(""))\r
1631                                         text = tr("Untitled Note");\r
1632                                 titleLabel.setText(text);\r
1633                         } else {\r
1634                                 if (text.length() > Constants.EDAM_NOTE_TITLE_LEN_MAX)\r
1635                                         titleLabel.setText(text.substring(0, Constants.EDAM_NOTE_TITLE_LEN_MAX));\r
1636                                 else {\r
1637                                         titleLabel.blockSignals(true);\r
1638                                         if (text.trim().equals(""))\r
1639                                                 titleLabel.setText(tr("Untitled Note"));\r
1640                                         else\r
1641                                                 titleLabel.setText(text);\r
1642                                         titleLabel.blockSignals(false);\r
1643                                 }\r
1644                         }\r
1645                         noteSignal.titleChanged.emit(currentNote.getGuid(), titleLabel\r
1646                                         .text());\r
1647                 }\r
1648         }\r
1649 \r
1650         // Return the note contents so we can email them\r
1651         public String getContentsToEmail() {\r
1652                 return browser.page().currentFrame().toPlainText().trim();\r
1653                 /*\r
1654                  * int body = browser.page().currentFrame().toHtml().indexOf("<body>");\r
1655                  * String temp = browser.page().currentFrame().toHtml(); if (body == -1)\r
1656                  * temp = "<html><body><b>Test</b></body></html>"; else temp =\r
1657                  * "<html>"+temp.substring(body); return temp; // return\r
1658                  * urlEncode(browser.page().currentFrame().toHtml());\r
1659                  */\r
1660         }\r
1661 \r
1662         // Insert an image into the editor\r
1663         private void insertImage(QMimeData mime) {\r
1664                 logger.log(logger.EXTREME, "Entering insertImage");\r
1665                 QImage img = (QImage) mime.imageData();\r
1666                 String script_start = new String(\r
1667                                 "document.execCommand('insertHTML', false, '");\r
1668                 String script_end = new String("');");\r
1669 \r
1670                 long now = new Date().getTime();\r
1671                 String path = Global.getFileManager().getResDirPath(\r
1672                                 (new Long(now).toString()) + ".jpg");\r
1673 \r
1674                 // This block is just a hack to make sure we wait at least 1ms so we\r
1675                 // don't\r
1676                 // have collisions on image names\r
1677                 long i = new Date().getTime();\r
1678                 while (now == i)\r
1679                         i = new Date().getTime();\r
1680 \r
1681                 // Open the file & write the data\r
1682                 QFile tfile = new QFile(path);\r
1683                 tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));\r
1684                 img.save(tfile);\r
1685                 tfile.close();\r
1686                 \r
1687                 Resource newRes = createResource(QUrl.fromLocalFile(path).toString(), 0, "image/jpeg", false);\r
1688                 if (newRes == null)\r
1689                         return;\r
1690                 currentNote.getResources().add(newRes);\r
1691 \r
1692                 // do the actual insert into the note\r
1693                 StringBuffer buffer = new StringBuffer(100);\r
1694                 buffer.append("<img src=\"");\r
1695                 buffer.append(tfile.fileName());\r
1696                 buffer.append("\" en-tag=en-media type=\"image/jpeg\""\r
1697                                 +" hash=\""+Global.byteArrayToHexString(newRes.getData().getBodyHash()) +"\""\r
1698                                 +" guid=\"" +newRes.getGuid() +"\""\r
1699 //                              +" onContextMenu=\"window.jambi.imageContextMenu('" +tfile.fileName() +"');\""\r
1700                                 +" onContextMenu=\"window.jambi.imageContextMenu(&amp." +tfile.fileName() +"&amp.);\""\r
1701                                 + " />");\r
1702                 \r
1703                 browser.page().mainFrame().evaluateJavaScript(\r
1704                                 script_start + buffer + script_end);\r
1705 \r
1706                 return;\r
1707         }\r
1708 \r
1709         // Handle URLs that are trying to be pasted\r
1710         public void handleUrls(QMimeData mime) {\r
1711                 logger.log(logger.EXTREME, "Starting handleUrls");\r
1712                 FileNameMap fileNameMap = URLConnection.getFileNameMap();\r
1713 \r
1714                 List<QUrl> urlList = mime.urls();\r
1715                 String url = new String();\r
1716                 String script_start = new String(\r
1717                                 "document.execCommand('createLink', false, '");\r
1718                 String script_end = new String("');");\r
1719 \r
1720                 for (int i = 0; i < urlList.size(); i++) {\r
1721                         url = urlList.get(i).toString();\r
1722                         // Find out what type of file we have\r
1723                         String mimeType = fileNameMap.getContentTypeFor(url);\r
1724 \r
1725                         // If null returned, we need to guess at the file type\r
1726                         if (mimeType == null)\r
1727                                 mimeType = "application/"\r
1728                                                 + url.substring(url.lastIndexOf(".") + 1);\r
1729 \r
1730                         // Check if we have an image or some other type of file\r
1731                         if (url.substring(0, 5).equalsIgnoreCase("file:")\r
1732                                         && mimeType.substring(0, 5).equalsIgnoreCase("image")) {\r
1733                                 handleLocalImageURLPaste(mime, mimeType);\r
1734                                 return;\r
1735                         }\r
1736                         String[] type = mimeType.split("/");\r
1737                         boolean valid = validAttachment(type[1]);\r
1738                         boolean smallEnough = checkFileAttachmentSize(url);\r
1739                         if (smallEnough && valid\r
1740                                         && url.substring(0, 5).equalsIgnoreCase("file:")\r
1741                                         && !mimeType.substring(0, 5).equalsIgnoreCase("image")) {\r
1742                                 handleLocalAttachment(mime, mimeType);\r
1743                                 return;\r
1744                         }\r
1745                         browser.page().mainFrame().evaluateJavaScript(\r
1746                                         script_start + url + script_end);\r
1747                 }\r
1748                 return;\r
1749         }\r
1750 \r
1751         // If a URL being pasted is an image URL, then attach the image\r
1752         private void handleLocalImageURLPaste(QMimeData mime, String mimeType) {\r
1753                 List<QUrl> urlList = mime.urls();\r
1754                 String url = new String();\r
1755                 String script_start_image = new String(\r
1756                                 "document.execCommand('insertHtml', false, '");\r
1757                 String script_end = new String("');");\r
1758                 StringBuffer buffer;\r
1759 \r
1760                 // Copy the image over into the resource directory and create a new resource \r
1761                 // record for each url pasted\r
1762                 for (int i = 0; i < urlList.size(); i++) {\r
1763                         url = urlList.get(i).toString();\r
1764 \r
1765                         Resource newRes = createResource(url, i, mimeType, false);\r
1766                         if (newRes == null)\r
1767                                 return;\r
1768                         currentNote.getResources().add(newRes);\r
1769                         buffer = new StringBuffer(100);\r
1770                         \r
1771                         // Open the file & write the data\r
1772                         String fileName = Global.getFileManager().getResDirPath(newRes.getGuid());\r
1773                         QFile tfile = new QFile(fileName);\r
1774                         tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));\r
1775                         tfile.write(newRes.getData().getBody());\r
1776                         tfile.close();\r
1777                         buffer.append(script_start_image);\r
1778                         buffer.append("<img src=\"" + FileUtils.toForwardSlashedPath(fileName));\r
1779 //                      if (mimeType.equalsIgnoreCase("image/jpg"))\r
1780 //                              mimeType = "image/jpeg";\r
1781                         buffer.append("\" en-tag=\"en-media\" type=\"" + mimeType +"\""\r
1782                                         +" hash=\""+Global.byteArrayToHexString(newRes.getData().getBodyHash()) +"\""\r
1783                                         +" guid=\"" +newRes.getGuid() +"\""\r
1784                                         +" onContextMenu=\"window.jambi.imageContextMenu(&apos;" +tfile.fileName() +"&apos;);\""\r
1785                                         + " />");\r
1786                         buffer.append(script_end);\r
1787                         browser.page().mainFrame().evaluateJavaScript(buffer.toString());\r
1788                 }\r
1789                 return;\r
1790         }\r
1791         \r
1792 \r
1793         // If a URL being pasted is a local file URL, then attach the file\r
1794         private void handleLocalAttachment(QMimeData mime, String mimeType) {\r
1795                 logger.log(logger.EXTREME, "Attaching local file");\r
1796                 List<QUrl> urlList = mime.urls();\r
1797                 String script_start = new String(\r
1798                                 "document.execCommand('insertHtml', false, '");\r
1799                 String script_end = new String("');");\r
1800                 StringBuffer buffer;\r
1801 \r
1802                         String[] type = mimeType.split("/");\r
1803                         String icon = findIcon(type[1]);\r
1804                         if (icon.equals("attachment.png"))\r
1805                                 icon = findIcon(type[0]);\r
1806                         buffer = new StringBuffer(100);\r
1807 \r
1808                 for (int i = 0; i < urlList.size(); i++) {\r
1809                         String url = urlList.get(i).toString();\r
1810 \r
1811                         // Start building the HTML\r
1812                         if (icon.equals("attachment.png"))\r
1813                                 icon = findIcon(url.substring(url.lastIndexOf(".")+1));\r
1814                         String imageURL = FileUtils.toFileURLString(Global.getFileManager().getImageDirFile(icon));\r
1815 \r
1816                         logger.log(logger.EXTREME, "Creating resource ");\r
1817                         Resource newRes = createResource(url, i, mimeType, true);\r
1818                         if (newRes == null)\r
1819                                 return;\r
1820                         logger.log(logger.EXTREME, "New resource size: " +newRes.getData().getSize());\r
1821                         currentNote.getResources().add(newRes);\r
1822                         \r
1823                         String fileName = newRes.getGuid() + Global.attachmentNameDelimeter+newRes.getAttributes().getFileName();\r
1824                         // If we have a PDF, we need to setup the preview.\r
1825                         if (icon.equalsIgnoreCase("pdf.png") && Global.pdfPreview()) {\r
1826                                 logger.log(logger.EXTREME, "Setting up PDF preview");\r
1827                                 if (newRes.getAttributes() != null && \r
1828                                                 newRes.getAttributes().getFileName() != null && \r
1829                                                 !newRes.getAttributes().getFileName().trim().equals(""))\r
1830                                         fileName = newRes.getGuid()+Global.attachmentNameDelimeter+\r
1831                                                 newRes.getAttributes().getFileName();\r
1832                                 else\r
1833                                         fileName = newRes.getGuid()+".pdf";\r
1834                                 QFile file = new QFile(Global.getFileManager().getResDirPath(fileName));\r
1835                         QFile.OpenMode mode = new QFile.OpenMode();\r
1836                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
1837                         file.open(mode);\r
1838                         QDataStream out = new QDataStream(file);\r
1839 //                      Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(newRes.getGuid(), true);\r
1840                                 QByteArray binData = new QByteArray(newRes.getData().getBody());\r
1841 //                              resBinary = null;\r
1842                         out.writeBytes(binData.toByteArray());\r
1843                         file.close();\r
1844 \r
1845                                 PDFPreview pdfPreview = new PDFPreview();\r
1846                                 if (pdfPreview.setupPreview(Global.getFileManager().getResDirPath(fileName), "pdf",0)) {\r
1847                                 // NFC TODO: should this be a 'file://' url like the ones above?\r
1848                                 imageURL = file.fileName() + ".png";\r
1849                                 }\r
1850                         }\r
1851                                                 \r
1852                         logger.log(logger.EXTREME, "Generating link tags");\r
1853                         buffer.delete(0, buffer.length());\r
1854                         buffer.append("<a en-tag=\"en-media\" guid=\"" +newRes.getGuid()+"\" ");\r
1855                         buffer.append(" onContextMenu=\"window.jambi.imageContextMenu(&apos;")\r
1856                       .append(Global.getFileManager().getResDirPath(fileName))\r
1857                       .append("&apos;);\" ");                   buffer.append("type=\"" + mimeType + "\" href=\"nnres://" + fileName +"\" hash=\""+Global.byteArrayToHexString(newRes.getData().getBodyHash()) +"\" >");\r
1858                         buffer.append("<img src=\"" + imageURL + "\" title=\"" +newRes.getAttributes().getFileName());\r
1859                         buffer.append("\"></img>");\r
1860                         buffer.append("</a>");\r
1861                         browser.page().mainFrame().evaluateJavaScript(\r
1862                                         script_start + buffer.toString() + script_end);\r
1863                 }\r
1864                 return;\r
1865         }\r
1866 \r
1867         private Resource createResource(String url, int sequence, String mime, boolean attachment) {\r
1868                 logger.log(logger.EXTREME, "Inside create resource");\r
1869                 QFile resourceFile;\r
1870                 String urlTest = new QUrl(url).toLocalFile();\r
1871                 if (!urlTest.equals(""))\r
1872                         url = urlTest;\r
1873                 url = url.replace("/", File.separator);\r
1874         resourceFile = new QFile(url); \r
1875         resourceFile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly));\r
1876         byte[] fileData = resourceFile.readAll().toByteArray();\r
1877         resourceFile.close();\r
1878         if (fileData.length == 0)\r
1879                 return null;\r
1880         MessageDigest md;\r
1881         try {\r
1882                 md = MessageDigest.getInstance("MD5");\r
1883                 md.update(fileData);\r
1884                 byte[] hash = md.digest();\r
1885   \r
1886                 Resource r = new Resource();\r
1887                 Calendar time = new GregorianCalendar();\r
1888                 long prevTime = time.getTimeInMillis();\r
1889                 while (prevTime == time.getTimeInMillis()) {\r
1890                         time = new GregorianCalendar();\r
1891                 }\r
1892                 r.setGuid(time.getTimeInMillis()+new Integer(sequence).toString());\r
1893                 r.setNoteGuid(currentNote.getGuid());\r
1894                 r.setMime(mime);\r
1895                 r.setActive(true);\r
1896                 r.setUpdateSequenceNum(0);\r
1897                 r.setWidth((short) 0);\r
1898                 r.setHeight((short) 0);\r
1899                 r.setDuration((short) 0);\r
1900                                 \r
1901                 Data d = new Data();\r
1902                 d.setBody(fileData);\r
1903                 d.setBodyIsSet(true);\r
1904                 d.setBodyHash(hash);\r
1905                 d.setBodyHashIsSet(true);\r
1906                 r.setData(d);\r
1907                 d.setSize(fileData.length);\r
1908                 \r
1909                 int fileNamePos = url.lastIndexOf(File.separator);\r
1910                 if (fileNamePos == -1)\r
1911                         fileNamePos = url.lastIndexOf("/");\r
1912                         String fileName = url.substring(fileNamePos+1);\r
1913                 ResourceAttributes a = new ResourceAttributes();\r
1914                 a.setAltitude(0);\r
1915                 a.setAltitudeIsSet(false);\r
1916                 a.setLongitude(0);\r
1917                 a.setLongitudeIsSet(false);\r
1918                 a.setLatitude(0);\r
1919                 a.setLatitudeIsSet(false);\r
1920                 a.setCameraMake("");\r
1921                 a.setCameraMakeIsSet(false);\r
1922                 a.setCameraModel("");\r
1923                 a.setCameraModelIsSet(false);\r
1924                 a.setAttachment(attachment);\r
1925                 a.setAttachmentIsSet(true);\r
1926                 a.setClientWillIndex(false);\r
1927                 a.setClientWillIndexIsSet(true);\r
1928                 a.setRecoType("");\r
1929                 a.setRecoTypeIsSet(false);\r
1930                 a.setSourceURL(url);\r
1931                 a.setSourceURLIsSet(true);\r
1932                 a.setTimestamp(0);\r
1933                 a.setTimestampIsSet(false);\r
1934                 a.setFileName(fileName);\r
1935                 a.setFileNameIsSet(true);\r
1936                 r.setAttributes(a);\r
1937                 \r
1938                 conn.getNoteTable().noteResourceTable.saveNoteResource(r, true);\r
1939                 return r;\r
1940         } catch (NoSuchAlgorithmException e1) {\r
1941                 e1.printStackTrace();\r
1942                 }\r
1943         return null;\r
1944         }\r
1945         \r
1946 \r
1947     // find the appropriate icon for an attachment\r
1948     private String findIcon(String appl) {\r
1949         appl = appl.toLowerCase();\r
1950         File f = Global.getFileManager().getImageDirFile(appl + ".png");\r
1951         if (f.exists())\r
1952                 return appl+".png";\r
1953         return "attachment.png";\r
1954     }\r
1955 \r
1956         // Check if the account supports this type of attachment\r
1957         private boolean validAttachment(String type) {\r
1958                 if (Global.isPremium())\r
1959                         return true;\r
1960                 if (type.equalsIgnoreCase("JPG"))\r
1961                         return true;\r
1962                 if (type.equalsIgnoreCase("PNG"))\r
1963                         return true;\r
1964                 if (type.equalsIgnoreCase("GIF"))\r
1965                         return true;\r
1966                 if (type.equalsIgnoreCase("MP3"))\r
1967                         return true;\r
1968                 if (type.equalsIgnoreCase("WAV"))\r
1969                         return true;\r
1970                 if (type.equalsIgnoreCase("AMR"))\r
1971                         return true;\r
1972                 if (type.equalsIgnoreCase("PDF"))\r
1973                         return true;\r
1974                 String error = tr("Non-premium accounts can only attach JPG, PNG, GIF, MP3, WAV, AMR, or PDF files.");\r
1975                 QMessageBox.information(this, tr("Non-Premium Account"), error);\r
1976 \r
1977                 return false;\r
1978         }\r
1979 \r
1980         // Check the file attachment to be sure it isn't over 25 mb\r
1981         private boolean checkFileAttachmentSize(String url) {\r
1982                 String fileName = url.substring(8);\r
1983                 QFile resourceFile = new QFile(fileName);\r
1984                 resourceFile.open(new QIODevice.OpenMode(\r
1985                                 QIODevice.OpenModeFlag.ReadOnly));\r
1986                 long size = resourceFile.size();\r
1987                 resourceFile.close();\r
1988                 size = size / 1024 / 1024;\r
1989                 if (size < 50 && Global.isPremium())\r
1990                         return true;\r
1991                 if (size < 25)\r
1992                         return true;\r
1993 \r
1994                 String error = tr("A file attachment may not exceed 25MB.");\r
1995                 QMessageBox.information(this, tr("Attachment Size"), error);\r
1996                 return false;\r
1997         }\r
1998 \r
1999 \r
2000         @SuppressWarnings("unused")\r
2001         private void createdChanged() {\r
2002                 QDateTime dt = new QDateTime();\r
2003                 dt.setDate(createdDate.date());\r
2004                 dt.setTime(createdTime.time());\r
2005                 noteSignal.createdDateChanged.emit(currentNote.getGuid(), dt);\r
2006 \r
2007         }\r
2008 \r
2009         @SuppressWarnings("unused")\r
2010         private void alteredChanged() {\r
2011                 QDateTime dt = new QDateTime();\r
2012                 dt.setDate(alteredDate.date());\r
2013                 dt.setTime(alteredTime.time());\r
2014                 noteSignal.alteredDateChanged.emit(currentNote.getGuid(), dt);\r
2015         }\r
2016 \r
2017         @SuppressWarnings("unused")\r
2018         private void subjectDateTimeChanged() {\r
2019                 QDateTime dt = new QDateTime();\r
2020                 dt.setDate(subjectDate.date());\r
2021                 dt.setTime(subjectTime.time());\r
2022                 noteSignal.subjectDateChanged.emit(currentNote.getGuid(), dt);\r
2023 \r
2024         }\r
2025 \r
2026         @SuppressWarnings("unused")\r
2027         private void sourceUrlChanged() {\r
2028                 noteSignal.sourceUrlChanged.emit(currentNote.getGuid(), urlText.text());\r
2029         }\r
2030 \r
2031         @SuppressWarnings("unused")\r
2032         private void authorChanged() {\r
2033                 noteSignal.authorChanged.emit(currentNote.getGuid(), authorText.text());\r
2034         }\r
2035         \r
2036         @SuppressWarnings("unused")\r
2037         private void geoBoxChanged() {\r
2038                 int index = geoBox.currentIndex();\r
2039                 geoBox.setCurrentIndex(0);\r
2040                 if (index == 1) {\r
2041                         GeoDialog box = new GeoDialog();\r
2042                         box.setLongitude(currentNote.getAttributes().getLongitude());\r
2043                         box.setLatitude(currentNote.getAttributes().getLatitude());\r
2044                         box.setAltitude(currentNote.getAttributes().getAltitude());\r
2045                         box.exec();\r
2046                         if (!box.okPressed())\r
2047                                 return;\r
2048                         double alt = box.getAltitude();\r
2049                         double lat = box.getLatitude();\r
2050                         double lon = box.getLongitude();\r
2051                         if (alt != currentNote.getAttributes().getAltitude() ||\r
2052                                 lon != currentNote.getAttributes().getLongitude() ||\r
2053                                 lat != currentNote.getAttributes().getLatitude()) {\r
2054                                         noteSignal.geoChanged.emit(currentNote.getGuid(), lon, lat, alt);\r
2055                                         currentNote.getAttributes().setAltitude(alt);\r
2056                                         currentNote.getAttributes().setLongitude(lon);\r
2057                                         currentNote.getAttributes().setLatitude(lat);\r
2058                         }\r
2059                 }\r
2060                 \r
2061                 if (index == 2) {\r
2062                         noteSignal.geoChanged.emit(currentNote.getGuid(), 0.0, 0.0, 0.0);\r
2063                         currentNote.getAttributes().setAltitude(0.0);\r
2064                         currentNote.getAttributes().setLongitude(0.0);\r
2065                         currentNote.getAttributes().setLatitude(0.0);\r
2066                 }\r
2067                 \r
2068                 if (index == 3 || index == 0) {\r
2069                         QDesktopServices.openUrl(new QUrl("http://maps.google.com/maps?z=6&q="+currentNote.getAttributes().getLatitude() +"," +currentNote.getAttributes().getLongitude()));\r
2070                 }\r
2071         }\r
2072 \r
2073         // ************************************************************\r
2074         // * User chose to save an attachment. Pares out the request *\r
2075         // * into a guid & file. Save the result. *\r
2076         // ************************************************************\r
2077         public void downloadAttachment(QNetworkRequest request) {\r
2078                 String guid;\r
2079                 QFileDialog fd = new QFileDialog(this);\r
2080                 fd.setFileMode(FileMode.AnyFile);\r
2081                 fd.setConfirmOverwrite(true);\r
2082                 fd.setWindowTitle(tr("Save File"));\r
2083                 fd.setAcceptMode(AcceptMode.AcceptSave);\r
2084                 fd.setDirectory(System.getProperty("user.home"));\r
2085                 String name = request.url().toString();\r
2086 \r
2087                 int pos = name.lastIndexOf(Global.attachmentNameDelimeter);\r
2088                 if (pos > -1) {\r
2089                         guid = name.substring(0, pos).replace("nnres://", "");\r
2090                         name = name.substring(pos +Global.attachmentNameDelimeter.length());\r
2091                         fd.selectFile(name);\r
2092                         pos = name.lastIndexOf('.');\r
2093                         if (pos > -1) {\r
2094                                 String mimeType = "(*." + name.substring(pos + 1)\r
2095                                                 + ");; All Files (*)";\r
2096                                 fd.setFilter(tr(mimeType));\r
2097                         }\r
2098                 } else {\r
2099                         guid = name;\r
2100                 }\r
2101 \r
2102                 // Strip URL prefix and base dir\r
2103                 guid = guid.replace("nnres://", "")\r
2104                         .replace(FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath()), "");\r
2105 \r
2106                 pos = guid.lastIndexOf('.');\r
2107                 if (pos > 0)\r
2108                         guid = guid.substring(0,pos);\r
2109                 if (fd.exec() != 0 && fd.selectedFiles().size() > 0) {\r
2110                         name = name.replace('\\', '/');\r
2111                         Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);\r
2112                         QFile saveFile = new QFile(fd.selectedFiles().get(0));\r
2113                         QFile.OpenMode mode = new QFile.OpenMode();\r
2114                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
2115                         saveFile.open(mode);\r
2116                         QDataStream saveOut = new QDataStream(saveFile);\r
2117                         QByteArray binData = new QByteArray(resBinary.getData().getBody());\r
2118                         saveOut.writeBytes(binData.toByteArray());\r
2119                         saveFile.close();\r
2120 \r
2121                 }\r
2122         }\r
2123 \r
2124         \r
2125         // ************************************************************\r
2126         // * User chose to save an attachment. Pares out the request *\r
2127         // * into a guid & file. Save the result. --- DONE FROM downloadAttachment now!!!!!   \r
2128         // ************************************************************\r
2129         // NFC TODO: unused? remove\r
2130         public void downloadImage(QNetworkRequest request) {\r
2131                 QFileDialog fd = new QFileDialog(this);\r
2132                 fd.setFileMode(FileMode.AnyFile);\r
2133                 fd.setConfirmOverwrite(true);\r
2134                 fd.setWindowTitle(tr("Save File"));\r
2135                 fd.setAcceptMode(AcceptMode.AcceptSave);\r
2136                 fd.setDirectory(System.getProperty("user.home"));\r
2137                 String name = request.url().toString();\r
2138                 name = name.replace("nnres://", "");\r
2139                 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());\r
2140                 name = name.replace(dPath, "");\r
2141                 int pos = name.lastIndexOf('.');\r
2142                 String guid = name;\r
2143                 if (pos > -1) {\r
2144                         String mimeType = "(*." + name.substring(pos + 1)\r
2145                         + ");; All Files (*)";\r
2146                                 fd.setFilter(tr(mimeType));\r
2147                         guid = guid.substring(0,pos);\r
2148                 }\r
2149                 pos = name.lastIndexOf(Global.attachmentNameDelimeter);\r
2150                 if (pos > -1) {\r
2151                         guid = name.substring(0, pos);\r
2152                         fd.selectFile(name.substring(pos+Global.attachmentNameDelimeter.length()));             \r
2153                 }\r
2154                 if (fd.exec() != 0 && fd.selectedFiles().size() > 0) {\r
2155                         Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);\r
2156                         String fileName = fd.selectedFiles().get(0);\r
2157                         QFile saveFile = new QFile(fileName);\r
2158                         QFile.OpenMode mode = new QFile.OpenMode();\r
2159                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
2160                         saveFile.open(mode);\r
2161                         QDataStream saveOut = new QDataStream(saveFile);\r
2162                         QByteArray binData = new QByteArray(resBinary.getData().getBody());\r
2163                         saveOut.writeBytes(binData.toByteArray());\r
2164                         saveFile.close();\r
2165                 }\r
2166         }\r
2167 \r
2168         \r
2169         // *************************************************************\r
2170         // * decrypt any hidden text.  We could do an XML parse, but \r
2171         // * it is quicker here just to scan for an <img tag & do the fix\r
2172         // * the manual way\r
2173         // *************************************************************\r
2174         private void removeEncryption(String id, String plainText, boolean permanent, String slot) {\r
2175                 if (!permanent) {\r
2176                         plainText = " <en-crypt-temp slot=\""+slot  +"\">" +plainText+"</en-crypt-temp> ";\r
2177                 }\r
2178                 \r
2179                 String html = browser.page().mainFrame().toHtml();\r
2180                 String text = html;\r
2181                 int imagePos = html.indexOf("<img");\r
2182                 int endPos;\r
2183                 for ( ;imagePos>0; ) {\r
2184                         // Find the end tag\r
2185                         endPos = text.indexOf(">", imagePos);\r
2186                         String tag = text.substring(imagePos-1,endPos);\r
2187                         if (tag.indexOf("id=\""+id+"\"") > -1) {\r
2188                                         text = text.substring(0,imagePos) +plainText+text.substring(endPos+1);\r
2189                                                                                 \r
2190                                         browser.setContent(new QByteArray(text));\r
2191                                         contentChanged();\r
2192                         }\r
2193                         imagePos = text.indexOf("<img", imagePos+1);\r
2194                 }\r
2195         }\r
2196         \r
2197         \r
2198         //****************************************************************\r
2199         //* Focus shortcuts\r
2200         //****************************************************************\r
2201         @SuppressWarnings("unused")\r
2202         private void focusTitle() {\r
2203                 titleLabel.setFocus();\r
2204         }\r
2205         @SuppressWarnings("unused")\r
2206         private void focusTag() {\r
2207                 tagEdit.setFocus();\r
2208         }\r
2209         @SuppressWarnings("unused")\r
2210         private void focusNote() {\r
2211                 browser.setFocus();\r
2212         }\r
2213         @SuppressWarnings("unused")\r
2214         private void focusAuthor() {\r
2215                 authorLabel.setFocus();\r
2216         }\r
2217         @SuppressWarnings("unused")\r
2218         private void focusUrl() {\r
2219                 urlLabel.setFocus();\r
2220         }\r
2221         \r
2222 \r
2223         //*****************************************************************\r
2224         //* Set the document background color\r
2225         //*****************************************************************\r
2226         public void setBackgroundColor(String color) {\r
2227                 String js = "function changeBackground(color) {"\r
2228                         +"document.body.style.background = color;"\r
2229                         +"}" \r
2230                         +"changeBackground('" +color+"');";\r
2231                 browser.page().mainFrame().evaluateJavaScript(js);\r
2232                 contentChanged();\r
2233         }\r
2234         \r
2235         \r
2236         //****************************************************************\r
2237         //* MicroFocus changed\r
2238         //****************************************************************\r
2239         private void microFocusChanged() {\r
2240                 boldButton.setDown(false);\r
2241                 italicButton.setDown(false);\r
2242                 underlineButton.setDown(false);\r
2243                 browser.openAction.setEnabled(false);\r
2244                 browser.downloadAttachment.setEnabled(false);\r
2245                 browser.downloadImage.setEnabled(false);\r
2246                 browser.rotateImageLeft.setEnabled(false);\r
2247                 browser.rotateImageRight.setEnabled(false);\r
2248                 browser.insertTableAction.setEnabled(true);\r
2249                 browser.insertTableRowAction.setEnabled(false);\r
2250                 browser.deleteTableRowAction.setEnabled(false);\r
2251                 browser.insertLinkAction.setText(tr("Insert Hyperlink"));\r
2252                 currentHyperlink ="";\r
2253                 insideList = false;\r
2254                 forceTextPaste = false;\r
2255                 \r
2256                 String js = new String( "function getCursorPos() {"\r
2257                         +"var cursorPos;"\r
2258                         +"if (window.getSelection) {"\r
2259                         +"   var selObj = window.getSelection();"\r
2260                         +"   var selRange = selObj.getRangeAt(0);"\r
2261                         +"   var workingNode = window.getSelection().anchorNode.parentNode;"\r
2262                         +"   while(workingNode != null) { " \r
2263 //                      +"      window.jambi.printNode(workingNode.nodeName);"\r
2264                         +"      if (workingNode.nodeName=='EN-CRYPT-TEMP') window.jambi.forceTextPaste();"\r
2265                         +"      if (workingNode.nodeName=='B') window.jambi.boldActive();"\r
2266                         +"      if (workingNode.nodeName=='I') window.jambi.italicActive();"\r
2267                         +"      if (workingNode.nodeName=='U') window.jambi.underlineActive();"\r
2268                         +"      if (workingNode.nodeName=='UL') window.jambi.setInsideList();"\r
2269                         +"      if (workingNode.nodeName=='OL') window.jambi.setInsideList();"\r
2270                         +"      if (workingNode.nodeName=='LI') window.jambi.setInsideList();"\r
2271                         +"      if (workingNode.nodeName=='TBODY') window.jambi.setInsideTable();"\r
2272                         +"      if (workingNode.nodeName=='A') {for(var x = 0; x < workingNode.attributes.length; x++ ) {if (workingNode.attributes[x].nodeName.toLowerCase() == 'href') window.jambi.setInsideLink(workingNode.attributes[x].nodeValue);}}"\r
2273                         +"      if (workingNode.nodeName=='SPAN') {"\r
2274                         +"         if (workingNode.getAttribute('style') == 'text-decoration: underline;') window.jambi.underlineActive();"\r
2275                         +"      }"\r
2276                         +"      workingNode = workingNode.parentNode;"\r
2277                         +"   }"\r
2278                         +"}"\r
2279                         +"} getCursorPos();");\r
2280                 browser.page().mainFrame().evaluateJavaScript(js);\r
2281         }\r
2282         \r
2283         public void printNode(String n) {\r
2284                 System.out.println("Node Vaule: " +n);\r
2285         }\r
2286         \r
2287         \r
2288         //****************************************************************\r
2289         //* Insert a table row\r
2290         //****************************************************************\r
2291         public void insertTableRow() {\r
2292                 \r
2293                 String js = new String( "function insertTableRow() {"\r
2294                         +"   var selObj = window.getSelection();"\r
2295                         +"   var selRange = selObj.getRangeAt(0);"\r
2296                         +"   var workingNode = window.getSelection().anchorNode.parentNode;"\r
2297                         +"   var cellCount = 0;"\r
2298                         +"   while(workingNode != null) { " \r
2299                         +"      if (workingNode.nodeName.toLowerCase()=='tr') {"\r
2300                         +"           row = document.createElement('TR');"\r
2301                         +"           var nodes = workingNode.getElementsByTagName('td');"\r
2302                         +"           for (j=0; j<nodes.length; j=j+1) {"\r
2303                         +"              cell = document.createElement('TD');"\r
2304                         +"              cell.innerHTML='&nbsp;';"\r
2305                         +"              row.appendChild(cell);"\r
2306                         +"           }"                 \r
2307                         +"           workingNode.parentNode.insertBefore(row,workingNode.nextSibling);"\r
2308                         +"           return;"\r
2309                         +"      }"\r
2310                         +"      workingNode = workingNode.parentNode;"\r
2311                         +"   }"\r
2312                         +"} insertTableRow();");\r
2313                 browser.page().mainFrame().evaluateJavaScript(js);\r
2314                 contentChanged();\r
2315         }\r
2316         //****************************************************************\r
2317         //* Insert a table row\r
2318         //****************************************************************\r
2319         public void deleteTableRow() {\r
2320                 \r
2321                 String js = new String( "function deleteTableRow() {"\r
2322                         +"   var selObj = window.getSelection();"\r
2323                         +"   var selRange = selObj.getRangeAt(0);"\r
2324                         +"   var workingNode = window.getSelection().anchorNode.parentNode;"\r
2325                         +"   var cellCount = 0;"\r
2326                         +"   while(workingNode != null) { " \r
2327                         +"      if (workingNode.nodeName.toLowerCase()=='tr') {"\r
2328                         +"           workingNode.parentNode.removeChild(workingNode);"\r
2329                         +"           return;"\r
2330                         +"      }"\r
2331                         +"      workingNode = workingNode.parentNode;"\r
2332                         +"   }"\r
2333                         +"} deleteTableRow();");\r
2334                 browser.page().mainFrame().evaluateJavaScript(js);\r
2335                 contentChanged();\r
2336         }\r
2337         public void setInsideTable() {\r
2338                 browser.insertTableRowAction.setEnabled(true);\r
2339                 browser.deleteTableRowAction.setEnabled(true);\r
2340                 browser.insertTableAction.setEnabled(false);\r
2341                 browser.encryptAction.setEnabled(false);\r
2342         }\r
2343         \r
2344         public void setInsideLink(String link) {\r
2345                 browser.insertLinkAction.setText(tr("Edit Hyperlink"));\r
2346                 currentHyperlink = link;\r
2347         }\r
2348         \r
2349         public void italicActive() {\r
2350                 italicButton.setDown(true);\r
2351         }\r
2352         public void boldActive() {\r
2353                 boldButton.setDown(true);\r
2354         }\r
2355         public void underlineActive() {\r
2356                 underlineButton.setDown(true);\r
2357         }\r
2358         public void forceTextPaste() {\r
2359                 forceTextPaste = true;\r
2360         }\r
2361         public void imageContextMenu(String f) {\r
2362                 browser.downloadImage.setEnabled(true);\r
2363                 browser.rotateImageRight.setEnabled(true);\r
2364                 browser.rotateImageLeft.setEnabled(true);\r
2365                 browser.openAction.setEnabled(true);\r
2366                 selectedFile = f;\r
2367         }\r
2368         public void rotateImageRight() {\r
2369                 QWebSettings.setMaximumPagesInCache(0);\r
2370                 QWebSettings.setObjectCacheCapacities(0, 0, 0);\r
2371                 QImage image = new QImage(selectedFile);\r
2372                 QMatrix matrix = new QMatrix();\r
2373                 matrix.rotate( 90.0 );\r
2374                 image = image.transformed(matrix);\r
2375                 image.save(selectedFile);\r
2376                 QWebSettings.setMaximumPagesInCache(0);\r
2377                 QWebSettings.setObjectCacheCapacities(0, 0, 0);\r
2378                 browser.setHtml(browser.page().mainFrame().toHtml());\r
2379                 browser.reload();\r
2380                 contentChanged();\r
2381 //              resourceSignal.contentChanged.emit(selectedFile);\r
2382 \r
2383         }\r
2384         public void rotateImageLeft() {\r
2385                 QImage image = new QImage(selectedFile);\r
2386                 QMatrix matrix = new QMatrix();\r
2387                 matrix.rotate( -90.0 );\r
2388                 image = image.transformed(matrix);\r
2389                 image.save(selectedFile);\r
2390                 browser.setHtml(browser.page().mainFrame().toHtml());\r
2391                 browser.reload();\r
2392                 contentChanged();\r
2393 //              resourceSignal.contentChanged.emit(selectedFile);\r
2394         }\r
2395         public void resourceContextMenu(String f) {\r
2396                 browser.downloadAttachment.setEnabled(true);\r
2397                 browser.openAction.setEnabled(true);\r
2398                 selectedFile = f;\r
2399         }\r
2400         \r
2401         \r
2402         //****************************************************************\r
2403         //* Apply CSS style to specified word\r
2404         //****************************************************************\r
2405 /*      public void applyStyleToWords(String word, String style) {\r
2406                 QFile script = new QFile("D:\\NeverNote\\js\\hilight1.js");\r
2407                 script.open(OpenModeFlag.ReadOnly);\r
2408                 String s = script.readAll().toString();\r
2409                 String js = new String(s +" findit('"+word+"', '"+style+"');");\r
2410                 browser.page().mainFrame().evaluateJavaScript(js);\r
2411                 System.out.println(getContent());\r
2412         }\r
2413 */      \r
2414         //****************************************************************\r
2415         //* Someone tried to paste a resource between notes, so we need  *\r
2416         //* to do some special handling.                                 *\r
2417         //****************************************************************\r
2418         private String fixInternotePaste(String text) {\r
2419                 logger.log(logger.EXTREME, "Fixing internote paste");\r
2420                 String returnValue = fixInternotePasteSearch(text, "<img", "src=\"");\r
2421                 return fixInternotePasteSearch(returnValue, "<a", "href=\"nnres://");\r
2422         }\r
2423         private String fixInternotePasteSearch(String text, String type, String locTag) {\r
2424                 \r
2425                 // First, let's fix the images.\r
2426                 int startPos = text.indexOf(type);\r
2427                 int endPos;\r
2428                 for (; startPos>=0;) {\r
2429                         endPos = text.indexOf(">", startPos+1);\r
2430                         String segment = text.substring(startPos, endPos);\r
2431                         if (segment.indexOf("en-tag") > -1) {\r
2432                                 String newSegment = segment;\r
2433                                 \r
2434                                 int guidStartPos = segment.indexOf("guid=\"");\r
2435                                 int guidEndPos = segment.indexOf("\"", guidStartPos+7);\r
2436                                 String guid = segment.substring(guidStartPos+6,guidEndPos);\r
2437                                 \r
2438                                 int mimeStartPos = segment.indexOf("type");\r
2439                                 int mimeEndPos = segment.indexOf("\"", mimeStartPos+7);\r
2440                                 String mime = segment.substring(mimeStartPos+6,mimeEndPos);\r
2441 \r
2442                                 int srcStartPos = segment.indexOf("src");\r
2443                                 int srcEndPos = segment.indexOf("\"", srcStartPos+6);\r
2444                                 String src = segment.substring(srcStartPos+5,srcEndPos);\r
2445                                 \r
2446                                 Calendar currentTime = new GregorianCalendar();\r
2447                                 Long l = new Long(currentTime.getTimeInMillis());\r
2448                                 long prevTime = l;\r
2449                                 while (l==prevTime) {\r
2450                                         currentTime = new GregorianCalendar();\r
2451                                         l= new Long(currentTime.getTimeInMillis());\r
2452                                 }\r
2453                                 \r
2454                                 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);\r
2455                                 // if r==null, then the image doesn't exist (it was probably cut out of another note, so \r
2456                                 // we need to recereate it\r
2457                                 if (r==null) {\r
2458                                         r = createResource(src, 1, mime, false);\r
2459                                         if (r==null)\r
2460                                                 return "";\r
2461                                 }\r
2462                         String randint = new String(Long.toString(l));\r
2463                         String extension = null;\r
2464                         if (r.getMime()!= null) {\r
2465                                 extension = r.getMime().toLowerCase();\r
2466                                 if (extension.indexOf("/")>-1)\r
2467                                         extension = extension.substring(extension.indexOf("/")+1);\r
2468                         }\r
2469                         String newFile = randint;\r
2470                         if (r.getAttributes().getFileName() != null && r.getAttributes().getFileName() != "")\r
2471                                 if (!locTag.startsWith("src"))\r
2472                                         newFile = newFile+Global.attachmentNameDelimeter+r.getAttributes().getFileName();\r
2473                         r.setNoteGuid(currentNote.getGuid());\r
2474                         \r
2475                         r.setGuid(randint);\r
2476                         conn.getNoteTable().noteResourceTable.saveNoteResource(r, true);\r
2477                                 QFile f = new QFile(Global.getFileManager().getResDirPath(newFile));\r
2478                                 QByteArray bin = new QByteArray(r.getData().getBody());\r
2479                                 f.open(QFile.OpenModeFlag.WriteOnly);\r
2480                                 f.write(bin);\r
2481                                 f.close();\r
2482                                 newSegment = newSegment.replace("guid=\""+guid, "guid=\""+randint);\r
2483                                 currentNote.getResources().add(r);\r
2484                                 \r
2485                                 int startSrcPos = newSegment.indexOf(locTag);\r
2486                                 int endSrcPos = newSegment.indexOf("\"",startSrcPos+locTag.length()+1);\r
2487                                 String source; \r
2488                                 if (locTag.startsWith("src")) {\r
2489                                          source = newSegment.substring(startSrcPos+locTag.length(),endSrcPos);\r
2490                                                 newSegment = newSegment.replace(source,\r
2491                                                         FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath(newFile)));\r
2492                                 } else {\r
2493                                         source = newSegment.substring(startSrcPos+locTag.length(),endSrcPos);\r
2494                                         newSegment = newSegment.replace(source, newFile);\r
2495                                 }\r
2496                                 \r
2497                                 text = text.substring(0,startPos) + newSegment + text.substring(endPos);\r
2498                         }\r
2499                         startPos = text.indexOf(type, startPos+1);\r
2500                 }\r
2501                 return text;\r
2502         }\r
2503 \r
2504 \r
2505         public void nextPage(String file) {\r
2506                 logger.log(logger.EXTREME, "Starting nextPage()");\r
2507                 \r
2508                 Integer pageNumber;\r
2509                 if (previewPageList.containsKey(file))\r
2510                         pageNumber = previewPageList.get(file)+1;\r
2511                 else\r
2512                         pageNumber = 2;\r
2513                 previewPageList.remove(file);\r
2514                 previewPageList.put(file, pageNumber);\r
2515                 PDFPreview pdfPreview = new PDFPreview();\r
2516                 boolean goodPreview = pdfPreview.setupPreview(file, "pdf", pageNumber);\r
2517                 if (goodPreview) {\r
2518 \r
2519 //                      String html = getContent();\r
2520                         QWebSettings.setMaximumPagesInCache(0);\r
2521                         QWebSettings.setObjectCacheCapacities(0, 0, 0);\r
2522 //                      browser.setContent(new QByteArray());\r
2523                         browser.setHtml(browser.page().mainFrame().toHtml());\r
2524                         browser.reload();\r
2525 //                      browser.setContent(new QByteArray(html));\r
2526 //                      browser.triggerPageAction(WebAction.Reload);\r
2527 //                      pdfMouseOver(selectedFile);\r
2528                 }\r
2529         }\r
2530 \r
2531         public void previousPage(String file) {\r
2532                 logger.log(logger.EXTREME, "Starting previousPage()");\r
2533                 \r
2534                 Integer pageNumber;\r
2535                 if (previewPageList.containsKey(file))\r
2536                         pageNumber = previewPageList.get(file)-1;\r
2537                 else\r
2538                         pageNumber = 1;\r
2539                 previewPageList.remove(file);\r
2540                 previewPageList.put(file, pageNumber);\r
2541                 PDFPreview pdfPreview = new PDFPreview();\r
2542                 boolean goodPreview = pdfPreview.setupPreview(file, "pdf", pageNumber);\r
2543                 if (goodPreview) {\r
2544 \r
2545 //                      String html = getContent();\r
2546                         QWebSettings.setMaximumPagesInCache(0);\r
2547                         QWebSettings.setObjectCacheCapacities(0, 0, 0);\r
2548                         browser.setHtml(browser.page().mainFrame().toHtml());\r
2549                         browser.reload();\r
2550 //                      browser.setContent(new QByteArray(html));\r
2551 //                      browser.triggerPageAction(WebAction.Reload);\r
2552                 }\r
2553         }\r
2554         \r
2555 /*      public void pdfMouseOver(String name) { \r
2556                 int pageNumber;\r
2557                 if (previewPageList.containsKey(selectedFile))\r
2558                         pageNumber = previewPageList.get(selectedFile)+1;\r
2559                 else\r
2560                         pageNumber = 1;\r
2561                 \r
2562                 if (pageNumber <= 1)\r
2563                         browser.previousPageAction.setEnabled(false);\r
2564                 else\r
2565                         browser.previousPageAction.setEnabled(true);\r
2566                 \r
2567                 PDFPreview pdf = new PDFPreview();\r
2568                 int totalPages = pdf.getPageCount(name);\r
2569                 if (previewPageList.containsKey(selectedFile))\r
2570                         pageNumber = previewPageList.get(selectedFile)+1;\r
2571                 else\r
2572                         pageNumber = 1;\r
2573                 if (totalPages > pageNumber)\r
2574                         browser.nextPageAction.setEnabled(true);\r
2575                 else\r
2576                         browser.nextPageAction.setEnabled(false);\r
2577         }\r
2578         \r
2579 \r
2580         public void pdfMouseOut() { \r
2581 //              browser.nextPageAction.setVisible(false);\r
2582 //              browser.previousPageAction.setVisible(false);\r
2583         }\r
2584 */\r
2585         \r
2586         private void toggleUndoVisible(Boolean toggle) {\r
2587                 undoAction.setVisible(toggle);\r
2588                 Global.saveEditorButtonsVisible("undo", toggle);\r
2589         }\r
2590         private void toggleRedoVisible(Boolean toggle) {\r
2591                 redoAction.setVisible(toggle);\r
2592                 Global.saveEditorButtonsVisible("redo", toggle);\r
2593         }\r
2594         private void toggleCutVisible(Boolean toggle) {\r
2595                 cutAction.setVisible(toggle);\r
2596                 Global.saveEditorButtonsVisible("cut", toggle);\r
2597         }\r
2598         private void toggleCopyVisible(Boolean toggle) {\r
2599                 copyAction.setVisible(toggle);\r
2600                 Global.saveEditorButtonsVisible("copy", toggle);\r
2601         }\r
2602         private void togglePasteVisible(Boolean toggle) {\r
2603                 pasteAction.setVisible(toggle);\r
2604                 Global.saveEditorButtonsVisible("paste", toggle);\r
2605         }\r
2606         private void toggleBoldVisible(Boolean toggle) {\r
2607                 boldAction.setVisible(toggle);\r
2608                 Global.saveEditorButtonsVisible("bold", toggle);\r
2609         }\r
2610         private void toggleItalicVisible(Boolean toggle) {\r
2611                 italicAction.setVisible(toggle);\r
2612                 Global.saveEditorButtonsVisible("italic", toggle);\r
2613         }\r
2614         private void toggleUnderlineVisible(Boolean toggle) {\r
2615                 underlineAction.setVisible(toggle);\r
2616                 Global.saveEditorButtonsVisible("underline", toggle);\r
2617         }\r
2618         private void toggleStrikethroughVisible(Boolean toggle) {\r
2619                 strikethroughAction.setVisible(toggle);\r
2620                 Global.saveEditorButtonsVisible("strikethrough", toggle);\r
2621         }\r
2622         private void toggleLeftAlignVisible(Boolean toggle) {\r
2623                 leftAlignAction.setVisible(toggle);\r
2624                 Global.saveEditorButtonsVisible("alignLeft", toggle);\r
2625         }\r
2626         private void toggleRightAlignVisible(Boolean toggle) {\r
2627                 rightAlignAction.setVisible(toggle);\r
2628                 Global.saveEditorButtonsVisible("alignRight", toggle);\r
2629         }       \r
2630         private void toggleCenterAlignVisible(Boolean toggle) {\r
2631                 centerAlignAction.setVisible(toggle);\r
2632                 Global.saveEditorButtonsVisible("alignCenter", toggle);\r
2633         }\r
2634         private void toggleHLineVisible(Boolean toggle) {\r
2635                 hlineAction.setVisible(toggle);\r
2636                 Global.saveEditorButtonsVisible("hline", toggle);\r
2637         }\r
2638         private void toggleIndentVisible(Boolean toggle) {\r
2639                 indentAction.setVisible(toggle);\r
2640                 Global.saveEditorButtonsVisible("indent", toggle);\r
2641         }\r
2642         private void toggleTodoVisible(Boolean toggle) {\r
2643                 todoAction.setVisible(toggle);\r
2644                 Global.saveEditorButtonsVisible("todo", toggle);\r
2645         }\r
2646         private void toggleOutdentVisible(Boolean toggle) {\r
2647                 outdentAction.setVisible(toggle);\r
2648                 Global.saveEditorButtonsVisible("outdent", toggle);\r
2649         }\r
2650         private void toggleBulletListVisible(Boolean toggle) {\r
2651                 bulletListAction.setVisible(toggle);\r
2652                 Global.saveEditorButtonsVisible("bulletList", toggle);\r
2653         }\r
2654         private void toggleNumberListVisible(Boolean toggle) {\r
2655                 numberListAction.setVisible(toggle);\r
2656                 Global.saveEditorButtonsVisible("numberList", toggle);\r
2657         }\r
2658         private void toggleFontListVisible(Boolean toggle) {\r
2659                 fontListAction.setVisible(toggle);\r
2660                 Global.saveEditorButtonsVisible("font", toggle);\r
2661         }\r
2662         private void toggleFontColorVisible(Boolean toggle) {\r
2663                 fontColorAction.setVisible(toggle);\r
2664                 Global.saveEditorButtonsVisible("fontColor", toggle);\r
2665         }\r
2666         private void toggleFontSizeVisible(Boolean toggle) {\r
2667                 fontSizeAction.setVisible(toggle);\r
2668                 Global.saveEditorButtonsVisible("fontSize", toggle);\r
2669         }\r
2670         private void toggleFontHilightVisible(Boolean toggle) {\r
2671                 fontHilightAction.setVisible(toggle);\r
2672                 Global.saveEditorButtonsVisible("fontHilight", toggle);\r
2673         }\r
2674         private void toggleSpellCheckVisible(Boolean toggle) {\r
2675                 spellCheckAction.setVisible(toggle);\r
2676                 Global.saveEditorButtonsVisible("spellCheck", toggle);\r
2677         }\r
2678 \r
2679 \r
2680         private void setupDictionary() {\r
2681                 File wordList = new File(Global.getFileManager().getSpellDirPath()+Locale.getDefault()+".dic");\r
2682                 try {\r
2683                         dictionary = new SpellDictionaryHashMap(wordList);\r
2684                         spellChecker = new SpellChecker(dictionary);\r
2685                         \r
2686                         File userWordList;\r
2687                         userWordList = new File(Global.getFileManager().getSpellDirPathUser()+"user.dic");\r
2688                         \r
2689                         // Get the local user spell dictionary\r
2690                         try {\r
2691                                 userDictionary = new SpellDictionaryHashMap(userWordList);\r
2692                         } catch (FileNotFoundException e) {\r
2693                                 userWordList.createNewFile();\r
2694                                 userDictionary = new SpellDictionaryHashMap(userWordList);\r
2695                         } catch (IOException e) {\r
2696                                 userWordList.createNewFile();\r
2697                                 userDictionary = new SpellDictionaryHashMap(userWordList);\r
2698                         }\r
2699                         \r
2700                         spellListener = new SuggestionListener(this, spellChecker);\r
2701                         \r
2702                         // Add the user dictionary\r
2703                         spellChecker.addSpellCheckListener(spellListener);\r
2704                         spellChecker.setUserDictionary(userDictionary);\r
2705 \r
2706                 } catch (FileNotFoundException e) {\r
2707                         QMessageBox.critical(this, tr("Spell Check Error"), \r
2708                                         tr("Dictionary "+ Global.getFileManager().getSpellDirPath()+Locale.getDefault()+\r
2709                                                 ".dic was not found."));\r
2710                 } catch (IOException e) {\r
2711                         QMessageBox.critical(this, tr("Spell Check Error"), \r
2712                                         tr("Dictionary "+ Global.getFileManager().getSpellDirPath()+Locale.getDefault()+\r
2713                                                 ".dic is invalid."));\r
2714                 }\r
2715 \r
2716         }\r
2717         \r
2718         // Invoke spell checker dialog\r
2719         private void spellCheckClicked() {\r
2720 \r
2721                 if (spellChecker == null) {\r
2722                         setupDictionary();      \r
2723                 }\r
2724                 \r
2725                 // Read user settings\r
2726                 spellChecker.getConfiguration().setBoolean(Configuration.SPELL_IGNOREDIGITWORDS, \r
2727                                 Global.getSpellSetting(Configuration.SPELL_IGNOREDIGITWORDS));\r
2728                 spellChecker.getConfiguration().setBoolean(Configuration.SPELL_IGNOREINTERNETADDRESSES, \r
2729                                 Global.getSpellSetting(Configuration.SPELL_IGNOREINTERNETADDRESSES));\r
2730                 spellChecker.getConfiguration().setBoolean(Configuration.SPELL_IGNOREMIXEDCASE, \r
2731                                 Global.getSpellSetting(Configuration.SPELL_IGNOREMIXEDCASE));\r
2732                 spellChecker.getConfiguration().setBoolean(Configuration.SPELL_IGNOREUPPERCASE, \r
2733                                 Global.getSpellSetting(Configuration.SPELL_IGNOREUPPERCASE));\r
2734                 spellChecker.getConfiguration().setBoolean(Configuration.SPELL_IGNORESENTENCECAPITALIZATION, \r
2735                                 Global.getSpellSetting(Configuration.SPELL_IGNORESENTENCECAPITALIZATION));\r
2736 \r
2737                 spellListener.abortSpellCheck = false;\r
2738                 spellListener.errorsFound = false;\r
2739                 String content = getBrowser().page().mainFrame().toPlainText();\r
2740                 StringWordTokenizer tokenizer = new StringWordTokenizer(content);\r
2741                 if (!tokenizer.hasMoreWords())\r
2742                         return;\r
2743                 getBrowser().page().action(WebAction.MoveToStartOfDocument);\r
2744 \r
2745                 getBrowser().setFocus();\r
2746                 boolean found;\r
2747                         \r
2748                 // Move to the start of page\r
2749                 KeyboardModifiers ctrl = new KeyboardModifiers(KeyboardModifier.ControlModifier.value());\r
2750                 QKeyEvent home = new QKeyEvent(Type.KeyPress, Key.Key_Home.value(), ctrl);  \r
2751                 browser.keyPressEvent(home);\r
2752                 getBrowser().setFocus();\r
2753                         \r
2754                 tokenizer = new StringWordTokenizer(content);\r
2755                 String word;\r
2756                         \r
2757                 while(tokenizer.hasMoreWords()) {\r
2758                         word = tokenizer.nextWord();\r
2759                         found = getBrowser().page().findText(word);\r
2760                         if (found && !spellListener.abortSpellCheck) {\r