OSDN Git Service

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