OSDN Git Service

Improved performance in the editor by not forcing a search through the note table...
[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         // The notebook selection has changed\r
1431         @SuppressWarnings("unused")\r
1432         private void notebookChanged() {\r
1433                 boolean changed = false;\r
1434                 String n = notebookBox.currentText();\r
1435                 for (int i = 0; i < notebookList.size(); i++) {\r
1436                         if (n.equals(notebookList.get(i).getName())) {\r
1437                                 if (!notebookList.get(i).getGuid().equals(currentNote.getNotebookGuid())) {\r
1438                                         currentNote.setNotebookGuid(notebookList.get(i).getGuid());\r
1439                                         changed = true;\r
1440                                 }\r
1441                                 i = notebookList.size();\r
1442                         }\r
1443                 }\r
1444                 \r
1445                 // If the notebook changed, signal the update\r
1446                 if (changed)\r
1447                         noteSignal.notebookChanged.emit(currentNote.getGuid(), currentNote\r
1448                                         .getNotebookGuid());\r
1449         }\r
1450 \r
1451         // Check the note title\r
1452         private void checkNoteTitle() {\r
1453                 String text = browser.page().currentFrame().toPlainText();\r
1454                 if (saveNoteTitle.trim().equals("")) {\r
1455                         int newLine = text.indexOf("\n");\r
1456                         if (newLine > 0) {\r
1457                                 text = text.substring(0, newLine);\r
1458                                 if (text.trim().equals(""))\r
1459                                         text = tr("Untitled Note");\r
1460                                 titleLabel.setText(text);\r
1461                         } else {\r
1462                                 if (text.length() > 20)\r
1463                                         titleLabel.setText(text.substring(0, 20));\r
1464                                 else {\r
1465                                         if (text.trim().equals(""))\r
1466                                                 titleLabel.setText(tr("Untitled Note"));\r
1467                                         else\r
1468                                                 titleLabel.setText(text);\r
1469                                 }\r
1470                         }\r
1471                         noteSignal.titleChanged.emit(currentNote.getGuid(), titleLabel\r
1472                                         .text());\r
1473                 }\r
1474         }\r
1475 \r
1476         // Return the note contents so we can email them\r
1477         public String getContentsToEmail() {\r
1478                 return browser.page().currentFrame().toPlainText().trim();\r
1479                 /*\r
1480                  * int body = browser.page().currentFrame().toHtml().indexOf("<body>");\r
1481                  * String temp = browser.page().currentFrame().toHtml(); if (body == -1)\r
1482                  * temp = "<html><body><b>Test</b></body></html>"; else temp =\r
1483                  * "<html>"+temp.substring(body); return temp; // return\r
1484                  * urlEncode(browser.page().currentFrame().toHtml());\r
1485                  */\r
1486         }\r
1487 \r
1488         // Insert an image into the editor\r
1489         private void insertImage(QMimeData mime) {\r
1490                 logger.log(logger.EXTREME, "Entering insertImage");\r
1491                 QImage img = (QImage) mime.imageData();\r
1492                 String script_start = new String(\r
1493                                 "document.execCommand('insertHTML', false, '");\r
1494                 String script_end = new String("');");\r
1495 \r
1496                 long now = new Date().getTime();\r
1497                 String path = Global.getFileManager().getResDirPath(\r
1498                                 (new Long(now).toString()) + ".jpg");\r
1499 \r
1500                 // This block is just a hack to make sure we wait at least 1ms so we\r
1501                 // don't\r
1502                 // have collisions on image names\r
1503                 long i = new Date().getTime();\r
1504                 while (now == i)\r
1505                         i = new Date().getTime();\r
1506 \r
1507                 // Open the file & write the data\r
1508                 QFile tfile = new QFile(path);\r
1509                 tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));\r
1510                 img.save(tfile);\r
1511                 tfile.close();\r
1512                 \r
1513                 Resource newRes = createResource(QUrl.fromLocalFile(path).toString(), 0, "image/jpeg", false);\r
1514                 if (newRes == null)\r
1515                         return;\r
1516                 currentNote.getResources().add(newRes);\r
1517 \r
1518                 // do the actual insert into the note\r
1519                 StringBuffer buffer = new StringBuffer(100);\r
1520                 buffer.append("<img src=\"");\r
1521                 buffer.append(tfile.fileName());\r
1522                 buffer.append("\" en-tag=en-media type=\"image/jpeg\""\r
1523                                 +" hash=\""+Global.byteArrayToHexString(newRes.getData().getBodyHash()) +"\""\r
1524                                 +" guid=\"" +newRes.getGuid() +"\""\r
1525                                 +" onContextMenu=\"window.jambi.imageContextMenu('" +tfile.fileName() +"');\""\r
1526                                 + " />");\r
1527                 browser.page().mainFrame().evaluateJavaScript(\r
1528                                 script_start + buffer + script_end);\r
1529 \r
1530                 return;\r
1531         }\r
1532 \r
1533         // Handle URLs that are trying to be pasted\r
1534         public void handleUrls(QMimeData mime) {\r
1535                 logger.log(logger.EXTREME, "Starting handleUrls");\r
1536                 FileNameMap fileNameMap = URLConnection.getFileNameMap();\r
1537 \r
1538                 List<QUrl> urlList = mime.urls();\r
1539                 String url = new String();\r
1540                 String script_start = new String(\r
1541                                 "document.execCommand('createLink', false, '");\r
1542                 String script_end = new String("');");\r
1543 \r
1544                 for (int i = 0; i < urlList.size(); i++) {\r
1545                         url = urlList.get(i).toString();\r
1546                         // Find out what type of file we have\r
1547                         String mimeType = fileNameMap.getContentTypeFor(url);\r
1548 \r
1549                         // If null returned, we need to guess at the file type\r
1550                         if (mimeType == null)\r
1551                                 mimeType = "application/"\r
1552                                                 + url.substring(url.lastIndexOf(".") + 1);\r
1553 \r
1554                         // Check if we have an image or some other type of file\r
1555                         if (url.substring(0, 5).equalsIgnoreCase("file:")\r
1556                                         && mimeType.substring(0, 5).equalsIgnoreCase("image")) {\r
1557                                 handleLocalImageURLPaste(mime, mimeType);\r
1558                                 return;\r
1559                         }\r
1560                         String[] type = mimeType.split("/");\r
1561                         boolean valid = validAttachment(type[1]);\r
1562                         boolean smallEnough = checkFileAttachmentSize(url);\r
1563                         if (smallEnough && valid\r
1564                                         && url.substring(0, 5).equalsIgnoreCase("file:")\r
1565                                         && !mimeType.substring(0, 5).equalsIgnoreCase("image")) {\r
1566                                 handleLocalAttachment(mime, mimeType);\r
1567                                 return;\r
1568                         }\r
1569                         browser.page().mainFrame().evaluateJavaScript(\r
1570                                         script_start + url + script_end);\r
1571                 }\r
1572                 return;\r
1573         }\r
1574 \r
1575         // If a URL being pasted is an image URL, then attach the image\r
1576         private void handleLocalImageURLPaste(QMimeData mime, String mimeType) {\r
1577                 List<QUrl> urlList = mime.urls();\r
1578                 String url = new String();\r
1579                 String script_start_image = new String(\r
1580                                 "document.execCommand('insertHtml', false, '");\r
1581                 String script_end = new String("');");\r
1582                 StringBuffer buffer;\r
1583 \r
1584                 // Copy the image over into the resource directory and create a new resource \r
1585                 // record for each url pasted\r
1586                 for (int i = 0; i < urlList.size(); i++) {\r
1587                         url = urlList.get(i).toString();\r
1588 \r
1589                         Resource newRes = createResource(url, i, mimeType, false);\r
1590                         if (newRes == null)\r
1591                                 return;\r
1592                         currentNote.getResources().add(newRes);\r
1593                         buffer = new StringBuffer(100);\r
1594                         \r
1595                         // Open the file & write the data\r
1596                         String fileName = Global.getFileManager().getResDirPath(newRes.getGuid());\r
1597                         QFile tfile = new QFile(fileName);\r
1598                         tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));\r
1599                         tfile.write(newRes.getData().getBody());\r
1600                         tfile.close();\r
1601                         buffer.append(script_start_image);\r
1602                         buffer.append("<img src=\"" + FileUtils.toForwardSlashedPath(fileName));\r
1603 //                      if (mimeType.equalsIgnoreCase("image/jpg"))\r
1604 //                              mimeType = "image/jpeg";\r
1605                         buffer.append("\" en-tag=\"en-media\" type=\"" + mimeType +"\""\r
1606                                         +" hash=\""+Global.byteArrayToHexString(newRes.getData().getBodyHash()) +"\""\r
1607                                         +" guid=\"" +newRes.getGuid() +"\""\r
1608                                         +" onContextMenu=\"window.jambi.imageContextMenu(&apos;" +tfile.fileName() +"&apos;);\""\r
1609                                         + " />");\r
1610                         buffer.append(script_end);\r
1611                         browser.page().mainFrame().evaluateJavaScript(buffer.toString());\r
1612                 }\r
1613                 return;\r
1614         }\r
1615         \r
1616 \r
1617         // If a URL being pasted is a local file URL, then attach the file\r
1618         private void handleLocalAttachment(QMimeData mime, String mimeType) {\r
1619                 logger.log(logger.EXTREME, "Attaching local file");\r
1620                 List<QUrl> urlList = mime.urls();\r
1621                 String script_start = new String(\r
1622                                 "document.execCommand('insertHtml', false, '");\r
1623                 String script_end = new String("');");\r
1624                 StringBuffer buffer;\r
1625 \r
1626                 for (int i = 0; i < urlList.size(); i++) {\r
1627                         buffer = new StringBuffer(100);\r
1628                         String url = urlList.get(i).toString();\r
1629 \r
1630                         // Start building the HTML\r
1631                         String[] type = mimeType.split("/");\r
1632                         String icon = findIcon(type[1]);\r
1633                         if (icon.equals("attachment.png"))\r
1634                                 icon = findIcon(type[0]);\r
1635                         if (icon.equals("attachment.png"))\r
1636                                 icon = findIcon(url.substring(url.lastIndexOf(".")+1));\r
1637                         StringBuffer imageBuffer = new StringBuffer();\r
1638                         String imageURL = FileUtils.toFileURLString(Global.getFileManager().getImageDirFile(icon));\r
1639 \r
1640                         logger.log(logger.EXTREME, "Creating resource ");\r
1641                         Resource newRes = createResource(url, i, mimeType, true);\r
1642                         if (newRes == null)\r
1643                                 return;\r
1644                         logger.log(logger.EXTREME, "New resource size: " +newRes.getData().getSize());\r
1645                         currentNote.getResources().add(newRes);\r
1646                         \r
1647                         String fileName = newRes.getGuid() + Global.attachmentNameDelimeter+newRes.getAttributes().getFileName();\r
1648                         // If we have a PDF, we need to setup the preview.\r
1649                         if (icon.equalsIgnoreCase("pdf.png") && Global.pdfPreview()) {\r
1650                                 logger.log(logger.EXTREME, "Setting up PDF preview");\r
1651                                 if (newRes.getAttributes() != null && \r
1652                                                 newRes.getAttributes().getFileName() != null && \r
1653                                                 !newRes.getAttributes().getFileName().trim().equals(""))\r
1654                                         fileName = newRes.getGuid()+Global.attachmentNameDelimeter+\r
1655                                                 newRes.getAttributes().getFileName();\r
1656                                 else\r
1657                                         fileName = newRes.getGuid()+".pdf";\r
1658                                 QFile file = new QFile(Global.getFileManager().getResDirPath(fileName));\r
1659                         QFile.OpenMode mode = new QFile.OpenMode();\r
1660                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
1661                         file.open(mode);\r
1662                         QDataStream out = new QDataStream(file);\r
1663 //                      Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(newRes.getGuid(), true);\r
1664                                 QByteArray binData = new QByteArray(newRes.getData().getBody());\r
1665 //                              resBinary = null;\r
1666                         out.writeBytes(binData.toByteArray());\r
1667                         file.close();\r
1668 \r
1669                                 PDFPreview pdfPreview = new PDFPreview();\r
1670                                 if (pdfPreview.setupPreview(Global.getFileManager().getResDirPath(fileName), "pdf",0)) {\r
1671                                 // NFC TODO: should this be a 'file://' url like the ones above?\r
1672                                 imageURL = file.fileName() + ".png";\r
1673                                 }\r
1674                         }\r
1675                                                 \r
1676                         logger.log(logger.EXTREME, "Generating link tags");\r
1677                         buffer.append("<a en-tag=\"en-media\" guid=\"" +newRes.getGuid()+"\" ");\r
1678                         buffer.append(" onContextMenu=\"window.jambi.imageContextMenu(&apos;")\r
1679                       .append(Global.getFileManager().getResDirPath(fileName))\r
1680                       .append("&apos;);\" ");                   buffer.append("type=\"" + mimeType + "\" href=\"nnres://" + fileName +"\" hash=\""+Global.byteArrayToHexString(newRes.getData().getBodyHash()) +"\" >");\r
1681                         buffer.append("<img src=\"" + imageURL + "\" title=\"" +newRes.getAttributes().getFileName());\r
1682                         buffer.append("\"></img>");\r
1683                         buffer.append("</a>");\r
1684                         browser.page().mainFrame().evaluateJavaScript(\r
1685                                         script_start + buffer.toString() + script_end);\r
1686                 }\r
1687                 return;\r
1688         }\r
1689         private Resource createResource(String url, int sequence, String mime, boolean attachment) {\r
1690                 logger.log(logger.EXTREME, "Inside create resource");\r
1691                 QFile resourceFile;\r
1692                 url = new QUrl(url).toLocalFile();\r
1693                 url = url.replace("/", File.separator);\r
1694         resourceFile = new QFile(url); \r
1695         resourceFile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly));\r
1696         byte[] fileData = resourceFile.readAll().toByteArray();\r
1697         resourceFile.close();\r
1698         if (fileData.length == 0)\r
1699                 return null;\r
1700         MessageDigest md;\r
1701         try {\r
1702                 md = MessageDigest.getInstance("MD5");\r
1703                 md.update(fileData);\r
1704                 byte[] hash = md.digest();\r
1705   \r
1706                 Resource r = new Resource();\r
1707                 Calendar time = new GregorianCalendar();\r
1708                 long prevTime = time.getTimeInMillis();\r
1709                 while (prevTime == time.getTimeInMillis()) {\r
1710                         time = new GregorianCalendar();\r
1711                 }\r
1712                 r.setGuid(time.getTimeInMillis()+new Integer(sequence).toString());\r
1713                 r.setNoteGuid(currentNote.getGuid());\r
1714                 r.setMime(mime);\r
1715                 r.setActive(true);\r
1716                 r.setUpdateSequenceNum(0);\r
1717                 r.setWidth((short) 0);\r
1718                 r.setHeight((short) 0);\r
1719                 r.setDuration((short) 0);\r
1720                                 \r
1721                 Data d = new Data();\r
1722                 d.setBody(fileData);\r
1723                 d.setBodyIsSet(true);\r
1724                 d.setBodyHash(hash);\r
1725                 d.setBodyHashIsSet(true);\r
1726                 r.setData(d);\r
1727                 d.setSize(fileData.length);\r
1728                 \r
1729                 int fileNamePos = url.lastIndexOf(File.separator);\r
1730                 if (fileNamePos == -1)\r
1731                         fileNamePos = url.lastIndexOf("/");\r
1732                         String fileName = url.substring(fileNamePos+1);\r
1733                 ResourceAttributes a = new ResourceAttributes();\r
1734                 a.setAltitude(0);\r
1735                 a.setAltitudeIsSet(false);\r
1736                 a.setLongitude(0);\r
1737                 a.setLongitudeIsSet(false);\r
1738                 a.setLatitude(0);\r
1739                 a.setLatitudeIsSet(false);\r
1740                 a.setCameraMake("");\r
1741                 a.setCameraMakeIsSet(false);\r
1742                 a.setCameraModel("");\r
1743                 a.setCameraModelIsSet(false);\r
1744                 a.setAttachment(attachment);\r
1745                 a.setAttachmentIsSet(true);\r
1746                 a.setClientWillIndex(false);\r
1747                 a.setClientWillIndexIsSet(true);\r
1748                 a.setRecoType("");\r
1749                 a.setRecoTypeIsSet(false);\r
1750                 a.setSourceURL(url);\r
1751                 a.setSourceURLIsSet(true);\r
1752                 a.setTimestamp(0);\r
1753                 a.setTimestampIsSet(false);\r
1754                 a.setFileName(fileName);\r
1755                 a.setFileNameIsSet(true);\r
1756                 r.setAttributes(a);\r
1757                 \r
1758                 conn.getNoteTable().noteResourceTable.saveNoteResource(r, true);\r
1759                 return r;\r
1760         } catch (NoSuchAlgorithmException e1) {\r
1761                 e1.printStackTrace();\r
1762                 }\r
1763         return null;\r
1764         }\r
1765         \r
1766 \r
1767     // find the appropriate icon for an attachment\r
1768     private String findIcon(String appl) {\r
1769         appl = appl.toLowerCase();\r
1770         File f = Global.getFileManager().getImageDirFile(appl + ".png");\r
1771         if (f.exists())\r
1772                 return appl+".png";\r
1773         return "attachment.png";\r
1774     }\r
1775 \r
1776         // Check if the account supports this type of attachment\r
1777         private boolean validAttachment(String type) {\r
1778                 if (Global.isPremium())\r
1779                         return true;\r
1780                 if (type.equalsIgnoreCase("JPG"))\r
1781                         return true;\r
1782                 if (type.equalsIgnoreCase("PNG"))\r
1783                         return true;\r
1784                 if (type.equalsIgnoreCase("GIF"))\r
1785                         return true;\r
1786                 if (type.equalsIgnoreCase("MP3"))\r
1787                         return true;\r
1788                 if (type.equalsIgnoreCase("WAV"))\r
1789                         return true;\r
1790                 if (type.equalsIgnoreCase("AMR"))\r
1791                         return true;\r
1792                 if (type.equalsIgnoreCase("PDF"))\r
1793                         return true;\r
1794                 String error = tr("Non-premium accounts can only attach JPG, PNG, GIF, MP3, WAV, AMR, or PDF files.");\r
1795                 QMessageBox.information(this, tr("Non-Premium Account"), error);\r
1796 \r
1797                 return false;\r
1798         }\r
1799 \r
1800         // Check the file attachment to be sure it isn't over 25 mb\r
1801         private boolean checkFileAttachmentSize(String url) {\r
1802                 String fileName = url.substring(8);\r
1803                 QFile resourceFile = new QFile(fileName);\r
1804                 resourceFile.open(new QIODevice.OpenMode(\r
1805                                 QIODevice.OpenModeFlag.ReadOnly));\r
1806                 long size = resourceFile.size();\r
1807                 resourceFile.close();\r
1808                 size = size / 1024 / 1024;\r
1809                 if (size < 50 && Global.isPremium())\r
1810                         return true;\r
1811                 if (size < 25)\r
1812                         return true;\r
1813 \r
1814                 String error = tr("A file attachment may not exceed 25MB.");\r
1815                 QMessageBox.information(this, tr("Attachment Size"), error);\r
1816                 return false;\r
1817         }\r
1818 \r
1819 \r
1820         @SuppressWarnings("unused")\r
1821         private void createdChanged() {\r
1822                 QDateTime dt = new QDateTime();\r
1823                 dt.setDate(createdDate.date());\r
1824                 dt.setTime(createdTime.time());\r
1825                 noteSignal.createdDateChanged.emit(currentNote.getGuid(), dt);\r
1826 \r
1827         }\r
1828 \r
1829         @SuppressWarnings("unused")\r
1830         private void alteredChanged() {\r
1831                 QDateTime dt = new QDateTime();\r
1832                 dt.setDate(alteredDate.date());\r
1833                 dt.setTime(alteredTime.time());\r
1834                 noteSignal.alteredDateChanged.emit(currentNote.getGuid(), dt);\r
1835         }\r
1836 \r
1837         @SuppressWarnings("unused")\r
1838         private void subjectDateTimeChanged() {\r
1839                 QDateTime dt = new QDateTime();\r
1840                 dt.setDate(subjectDate.date());\r
1841                 dt.setTime(subjectTime.time());\r
1842                 noteSignal.subjectDateChanged.emit(currentNote.getGuid(), dt);\r
1843 \r
1844         }\r
1845 \r
1846         @SuppressWarnings("unused")\r
1847         private void sourceUrlChanged() {\r
1848                 noteSignal.sourceUrlChanged.emit(currentNote.getGuid(), urlText.text());\r
1849         }\r
1850 \r
1851         @SuppressWarnings("unused")\r
1852         private void authorChanged() {\r
1853                 noteSignal.authorChanged.emit(currentNote.getGuid(), authorText.text());\r
1854         }\r
1855         \r
1856         private void geoBoxChanged() {\r
1857                 int index = geoBox.currentIndex();\r
1858                 geoBox.setCurrentIndex(0);\r
1859                 if (index == 1) {\r
1860                         GeoDialog box = new GeoDialog();\r
1861                         box.setLongitude(currentNote.getAttributes().getLongitude());\r
1862                         box.setLatitude(currentNote.getAttributes().getLatitude());\r
1863                         box.setAltitude(currentNote.getAttributes().getAltitude());\r
1864                         box.exec();\r
1865                         if (!box.okPressed())\r
1866                                 return;\r
1867                         double alt = box.getAltitude();\r
1868                         double lat = box.getLatitude();\r
1869                         double lon = box.getLongitude();\r
1870                         if (alt != currentNote.getAttributes().getAltitude() ||\r
1871                                 lon != currentNote.getAttributes().getLongitude() ||\r
1872                                 lat != currentNote.getAttributes().getLatitude()) {\r
1873                                         noteSignal.geoChanged.emit(currentNote.getGuid(), lon, lat, alt);\r
1874                                         currentNote.getAttributes().setAltitude(alt);\r
1875                                         currentNote.getAttributes().setLongitude(lon);\r
1876                                         currentNote.getAttributes().setLatitude(lat);\r
1877                         }\r
1878                 }\r
1879                 \r
1880                 if (index == 2) {\r
1881                         noteSignal.geoChanged.emit(currentNote.getGuid(), 0.0, 0.0, 0.0);\r
1882                         currentNote.getAttributes().setAltitude(0.0);\r
1883                         currentNote.getAttributes().setLongitude(0.0);\r
1884                         currentNote.getAttributes().setLatitude(0.0);\r
1885                 }\r
1886                 \r
1887                 if (index == 3 || index == 0) {\r
1888                         QDesktopServices.openUrl(new QUrl("http://maps.google.com/maps?z=6&q="+currentNote.getAttributes().getLatitude() +"," +currentNote.getAttributes().getLongitude()));\r
1889                 }\r
1890         }\r
1891 \r
1892         // ************************************************************\r
1893         // * User chose to save an attachment. Pares out the request *\r
1894         // * into a guid & file. Save the result. *\r
1895         // ************************************************************\r
1896         public void downloadAttachment(QNetworkRequest request) {\r
1897                 String guid;\r
1898                 QFileDialog fd = new QFileDialog(this);\r
1899                 fd.setFileMode(FileMode.AnyFile);\r
1900                 fd.setConfirmOverwrite(true);\r
1901                 fd.setWindowTitle(tr("Save File"));\r
1902                 fd.setAcceptMode(AcceptMode.AcceptSave);\r
1903                 fd.setDirectory(System.getProperty("user.home"));\r
1904                 String name = request.url().toString();\r
1905 \r
1906                 int pos = name.lastIndexOf(Global.attachmentNameDelimeter);\r
1907                 if (pos > -1) {\r
1908                         guid = name.substring(0, pos).replace("nnres://", "");\r
1909                         name = name.substring(pos +Global.attachmentNameDelimeter.length());\r
1910                         fd.selectFile(name);\r
1911                         pos = name.lastIndexOf('.');\r
1912                         if (pos > -1) {\r
1913                                 String mimeType = "(*." + name.substring(pos + 1)\r
1914                                                 + ");; All Files (*)";\r
1915                                 fd.setFilter(tr(mimeType));\r
1916                         }\r
1917                 } else {\r
1918                         guid = name;\r
1919                 }\r
1920 \r
1921                 // Strip URL prefix and base dir\r
1922                 guid = guid.replace("nnres://", "")\r
1923                         .replace(FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath()), "");\r
1924 \r
1925                 pos = guid.lastIndexOf('.');\r
1926                 if (pos > 0)\r
1927                         guid = guid.substring(0,pos);\r
1928                 if (fd.exec() != 0 && fd.selectedFiles().size() > 0) {\r
1929                         name = name.replace('\\', '/');\r
1930                         Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);\r
1931                         QFile saveFile = new QFile(fd.selectedFiles().get(0));\r
1932                         QFile.OpenMode mode = new QFile.OpenMode();\r
1933                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
1934                         saveFile.open(mode);\r
1935                         QDataStream saveOut = new QDataStream(saveFile);\r
1936                         QByteArray binData = new QByteArray(resBinary.getData().getBody());\r
1937                         saveOut.writeBytes(binData.toByteArray());\r
1938                         saveFile.close();\r
1939 \r
1940                 }\r
1941         }\r
1942 \r
1943         \r
1944         // ************************************************************\r
1945         // * User chose to save an attachment. Pares out the request *\r
1946         // * into a guid & file. Save the result. --- DONE FROM downloadAttachment now!!!!!   \r
1947         // ************************************************************\r
1948         // NFC TODO: unused? remove\r
1949         public void downloadImage(QNetworkRequest request) {\r
1950                 QFileDialog fd = new QFileDialog(this);\r
1951                 fd.setFileMode(FileMode.AnyFile);\r
1952                 fd.setConfirmOverwrite(true);\r
1953                 fd.setWindowTitle(tr("Save File"));\r
1954                 fd.setAcceptMode(AcceptMode.AcceptSave);\r
1955                 fd.setDirectory(System.getProperty("user.home"));\r
1956                 String name = request.url().toString();\r
1957                 name = name.replace("nnres://", "");\r
1958                 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());\r
1959                 name = name.replace(dPath, "");\r
1960                 int pos = name.lastIndexOf('.');\r
1961                 String guid = name;\r
1962                 if (pos > -1) {\r
1963                         String mimeType = "(*." + name.substring(pos + 1)\r
1964                         + ");; All Files (*)";\r
1965                                 fd.setFilter(tr(mimeType));\r
1966                         guid = guid.substring(0,pos);\r
1967                 }\r
1968                 pos = name.lastIndexOf(Global.attachmentNameDelimeter);\r
1969                 if (pos > -1) {\r
1970                         guid = name.substring(0, pos);\r
1971                         fd.selectFile(name.substring(pos+Global.attachmentNameDelimeter.length()));             \r
1972                 }\r
1973                 if (fd.exec() != 0 && fd.selectedFiles().size() > 0) {\r
1974                         Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);\r
1975                         String fileName = fd.selectedFiles().get(0);\r
1976                         QFile saveFile = new QFile(fileName);\r
1977                         QFile.OpenMode mode = new QFile.OpenMode();\r
1978                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
1979                         saveFile.open(mode);\r
1980                         QDataStream saveOut = new QDataStream(saveFile);\r
1981                         QByteArray binData = new QByteArray(resBinary.getData().getBody());\r
1982                         saveOut.writeBytes(binData.toByteArray());\r
1983                         saveFile.close();\r
1984                 }\r
1985         }\r
1986 \r
1987         \r
1988         // *************************************************************\r
1989         // * decrypt any hidden text.  We could do an XML parse, but \r
1990         // * it is quicker here just to scan for an <img tag & do the fix\r
1991         // * the manual way\r
1992         // *************************************************************\r
1993         private void removeEncryption(String id, String plainText, boolean permanent, String slot) {\r
1994                 if (!permanent) {\r
1995                         plainText = " <en-crypt-temp slot=\""+slot  +"\">" +plainText+"</en-crypt-temp> ";\r
1996                 }\r
1997                 \r
1998                 String html = browser.page().mainFrame().toHtml();\r
1999                 String text = html;\r
2000                 int imagePos = html.indexOf("<img");\r
2001                 int endPos;\r
2002                 for ( ;imagePos>0; ) {\r
2003                         // Find the end tag\r
2004                         endPos = text.indexOf(">", imagePos);\r
2005                         String tag = text.substring(imagePos-1,endPos);\r
2006                         if (tag.indexOf("id=\""+id+"\"") > -1) {\r
2007                                         text = text.substring(0,imagePos) +plainText+text.substring(endPos+1);\r
2008                                                                                 \r
2009                                         browser.setContent(new QByteArray(text));\r
2010                                         contentChanged();\r
2011                         }\r
2012                         imagePos = text.indexOf("<img", imagePos+1);\r
2013                 }\r
2014         }\r
2015         \r
2016         \r
2017         //****************************************************************\r
2018         //* Focus shortcuts\r
2019         //****************************************************************\r
2020         @SuppressWarnings("unused")\r
2021         private void focusTitle() {\r
2022                 titleLabel.setFocus();\r
2023         }\r
2024         @SuppressWarnings("unused")\r
2025         private void focusTag() {\r
2026                 tagEdit.setFocus();\r
2027         }\r
2028         @SuppressWarnings("unused")\r
2029         private void focusNote() {\r
2030                 browser.setFocus();\r
2031         }\r
2032         @SuppressWarnings("unused")\r
2033         private void focusAuthor() {\r
2034                 authorLabel.setFocus();\r
2035         }\r
2036         @SuppressWarnings("unused")\r
2037         private void focusUrl() {\r
2038                 urlLabel.setFocus();\r
2039         }\r
2040         \r
2041 \r
2042         //*****************************************************************\r
2043         //* Set the document background color\r
2044         //*****************************************************************\r
2045         public void setBackgroundColor(String color) {\r
2046                 String js = "function changeBackground(color) {"\r
2047                         +"document.body.style.background = color;"\r
2048                         +"}" \r
2049                         +"changeBackground('" +color+"');";\r
2050                 browser.page().mainFrame().evaluateJavaScript(js);\r
2051                 contentChanged();\r
2052         }\r
2053         \r
2054         \r
2055         //****************************************************************\r
2056         //* MicroFocus changed\r
2057         //****************************************************************\r
2058         private void microFocusChanged() {\r
2059                 boldButton.setDown(false);\r
2060                 italicButton.setDown(false);\r
2061                 underlineButton.setDown(false);\r
2062                 browser.openAction.setEnabled(false);\r
2063                 browser.downloadAttachment.setEnabled(false);\r
2064                 browser.downloadImage.setEnabled(false);\r
2065                 browser.rotateImageLeft.setEnabled(false);\r
2066                 browser.rotateImageRight.setEnabled(false);\r
2067                 browser.insertTableAction.setEnabled(true);\r
2068                 browser.insertTableRowAction.setEnabled(false);\r
2069                 browser.deleteTableRowAction.setEnabled(false);\r
2070                 browser.insertLinkAction.setText(tr("Insert Hyperlink"));\r
2071                 currentHyperlink ="";\r
2072                 insideList = false;\r
2073                 forceTextPaste = false;\r
2074                 \r
2075                 String js = new String( "function getCursorPos() {"\r
2076                         +"var cursorPos;"\r
2077                         +"if (window.getSelection) {"\r
2078                         +"   var selObj = window.getSelection();"\r
2079                         +"   var selRange = selObj.getRangeAt(0);"\r
2080                         +"   var workingNode = window.getSelection().anchorNode.parentNode;"\r
2081                         +"   while(workingNode != null) { " \r
2082 //                      +"      window.jambi.printNode(workingNode.nodeName);"\r
2083                         +"      if (workingNode.nodeName=='EN-CRYPT-TEMP') window.jambi.forceTextPaste();"\r
2084                         +"      if (workingNode.nodeName=='B') window.jambi.boldActive();"\r
2085                         +"      if (workingNode.nodeName=='I') window.jambi.italicActive();"\r
2086                         +"      if (workingNode.nodeName=='U') window.jambi.underlineActive();"\r
2087                         +"      if (workingNode.nodeName=='UL') window.jambi.setInsideList();"\r
2088                         +"      if (workingNode.nodeName=='OL') window.jambi.setInsideList();"\r
2089                         +"      if (workingNode.nodeName=='LI') window.jambi.setInsideList();"\r
2090                         +"      if (workingNode.nodeName=='TBODY') window.jambi.setInsideTable();"\r
2091                         +"      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
2092                         +"      if (workingNode.nodeName=='SPAN') {"\r
2093                         +"         if (workingNode.getAttribute('style') == 'text-decoration: underline;') window.jambi.underlineActive();"\r
2094                         +"      }"\r
2095                         +"      workingNode = workingNode.parentNode;"\r
2096                         +"   }"\r
2097                         +"}"\r
2098                         +"} getCursorPos();");\r
2099                 browser.page().mainFrame().evaluateJavaScript(js);\r
2100         }\r
2101         \r
2102         public void printNode(String n) {\r
2103                 System.out.println("Node Vaule: " +n);\r
2104         }\r
2105         \r
2106         \r
2107         //****************************************************************\r
2108         //* Insert a table row\r
2109         //****************************************************************\r
2110         public void insertTableRow() {\r
2111                 \r
2112                 String js = new String( "function insertTableRow() {"\r
2113                         +"   var selObj = window.getSelection();"\r
2114                         +"   var selRange = selObj.getRangeAt(0);"\r
2115                         +"   var workingNode = window.getSelection().anchorNode.parentNode;"\r
2116                         +"   var cellCount = 0;"\r
2117                         +"   while(workingNode != null) { " \r
2118                         +"      if (workingNode.nodeName.toLowerCase()=='tr') {"\r
2119                         +"           row = document.createElement('TR');"\r
2120                         +"           var nodes = workingNode.getElementsByTagName('td');"\r
2121                         +"           for (j=0; j<nodes.length; j=j+1) {"\r
2122                         +"              cell = document.createElement('TD');"\r
2123                         +"              cell.innerHTML='&nbsp;';"\r
2124                         +"              row.appendChild(cell);"\r
2125                         +"           }"                 \r
2126                         +"           workingNode.parentNode.insertBefore(row,workingNode.nextSibling);"\r
2127                         +"           return;"\r
2128                         +"      }"\r
2129                         +"      workingNode = workingNode.parentNode;"\r
2130                         +"   }"\r
2131                         +"} insertTableRow();");\r
2132                 browser.page().mainFrame().evaluateJavaScript(js);\r
2133                 contentChanged();\r
2134         }\r
2135         //****************************************************************\r
2136         //* Insert a table row\r
2137         //****************************************************************\r
2138         public void deleteTableRow() {\r
2139                 \r
2140                 String js = new String( "function deleteTableRow() {"\r
2141                         +"   var selObj = window.getSelection();"\r
2142                         +"   var selRange = selObj.getRangeAt(0);"\r
2143                         +"   var workingNode = window.getSelection().anchorNode.parentNode;"\r
2144                         +"   var cellCount = 0;"\r
2145                         +"   while(workingNode != null) { " \r
2146                         +"      if (workingNode.nodeName.toLowerCase()=='tr') {"\r
2147                         +"           workingNode.parentNode.removeChild(workingNode);"\r
2148                         +"           return;"\r
2149                         +"      }"\r
2150                         +"      workingNode = workingNode.parentNode;"\r
2151                         +"   }"\r
2152                         +"} deleteTableRow();");\r
2153                 browser.page().mainFrame().evaluateJavaScript(js);\r
2154                 contentChanged();\r
2155         }\r
2156         public void setInsideTable() {\r
2157                 browser.insertTableRowAction.setEnabled(true);\r
2158                 browser.deleteTableRowAction.setEnabled(true);\r
2159                 browser.insertTableAction.setEnabled(false);\r
2160                 browser.encryptAction.setEnabled(false);\r
2161         }\r
2162         \r
2163         public void setInsideLink(String link) {\r
2164                 browser.insertLinkAction.setText(tr("Edit Hyperlink"));\r
2165                 currentHyperlink = link;\r
2166         }\r
2167         \r
2168         public void italicActive() {\r
2169                 italicButton.setDown(true);\r
2170         }\r
2171         public void boldActive() {\r
2172                 boldButton.setDown(true);\r
2173         }\r
2174         public void underlineActive() {\r
2175                 underlineButton.setDown(true);\r
2176         }\r
2177         public void forceTextPaste() {\r
2178                 forceTextPaste = true;\r
2179         }\r
2180         public void imageContextMenu(String f) {\r
2181                 browser.downloadImage.setEnabled(true);\r
2182                 browser.rotateImageRight.setEnabled(true);\r
2183                 browser.rotateImageLeft.setEnabled(true);\r
2184                 browser.openAction.setEnabled(true);\r
2185                 selectedFile = f;\r
2186         }\r
2187         public void rotateImageRight() {\r
2188                 QWebSettings.setMaximumPagesInCache(0);\r
2189                 QWebSettings.setObjectCacheCapacities(0, 0, 0);\r
2190                 QImage image = new QImage(selectedFile);\r
2191                 QMatrix matrix = new QMatrix();\r
2192                 matrix.rotate( 90.0 );\r
2193                 image = image.transformed(matrix);\r
2194                 image.save(selectedFile);\r
2195                 QWebSettings.setMaximumPagesInCache(0);\r
2196                 QWebSettings.setObjectCacheCapacities(0, 0, 0);\r
2197                 browser.setHtml(browser.page().mainFrame().toHtml());\r
2198                 browser.reload();\r
2199                 contentChanged();\r
2200 //              resourceSignal.contentChanged.emit(selectedFile);\r
2201 \r
2202         }\r
2203         public void rotateImageLeft() {\r
2204                 QImage image = new QImage(selectedFile);\r
2205                 QMatrix matrix = new QMatrix();\r
2206                 matrix.rotate( -90.0 );\r
2207                 image = image.transformed(matrix);\r
2208                 image.save(selectedFile);\r
2209                 browser.setHtml(browser.page().mainFrame().toHtml());\r
2210                 browser.reload();\r
2211                 contentChanged();\r
2212 //              resourceSignal.contentChanged.emit(selectedFile);\r
2213         }\r
2214         public void resourceContextMenu(String f) {\r
2215                 browser.downloadAttachment.setEnabled(true);\r
2216                 browser.openAction.setEnabled(true);\r
2217                 selectedFile = f;\r
2218         }\r
2219         \r
2220         \r
2221         //****************************************************************\r
2222         //* Apply CSS style to specified word\r
2223         //****************************************************************\r
2224 /*      public void applyStyleToWords(String word, String style) {\r
2225                 QFile script = new QFile("D:\\NeverNote\\js\\hilight1.js");\r
2226                 script.open(OpenModeFlag.ReadOnly);\r
2227                 String s = script.readAll().toString();\r
2228                 String js = new String(s +" findit('"+word+"', '"+style+"');");\r
2229                 browser.page().mainFrame().evaluateJavaScript(js);\r
2230                 System.out.println(getContent());\r
2231         }\r
2232 */      \r
2233         //****************************************************************\r
2234         //* Someone tried to paste a resource between notes, so we need  *\r
2235         //* to do some special handling.                                 *\r
2236         //****************************************************************\r
2237         private String fixInternotePaste(String text) {\r
2238                 logger.log(logger.EXTREME, "Fixing internote paste");\r
2239                 String returnValue = fixInternotePasteSearch(text, "<img", "src=\"");\r
2240                 return fixInternotePasteSearch(returnValue, "<a", "href=\"nnres://");\r
2241         }\r
2242         private String fixInternotePasteSearch(String text, String type, String locTag) {\r
2243                 \r
2244                 // First, let's fix the images.\r
2245                 int startPos = text.indexOf(type);\r
2246                 int endPos;\r
2247                 for (; startPos>=0;) {\r
2248                         endPos = text.indexOf(">", startPos+1);\r
2249                         String segment = text.substring(startPos, endPos);\r
2250                         if (segment.indexOf("en-tag") > -1) {\r
2251                                 String newSegment = segment;\r
2252                                 \r
2253                                 int guidStartPos = segment.indexOf("guid=\"");\r
2254                                 int guidEndPos = segment.indexOf("\"", guidStartPos+7);\r
2255                                 String guid = segment.substring(guidStartPos+6,guidEndPos);\r
2256                                 \r
2257                                 Calendar currentTime = new GregorianCalendar();\r
2258                                 Long l = new Long(currentTime.getTimeInMillis());\r
2259                                 long prevTime = l;\r
2260                                 while (l==prevTime) {\r
2261                                         currentTime = new GregorianCalendar();\r
2262                                         l= new Long(currentTime.getTimeInMillis());\r
2263                                 }\r
2264                                 \r
2265                                 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);\r
2266                                 if (r==null)\r
2267                                         return "";\r
2268                         String randint = new String(Long.toString(l));\r
2269                         String extension = null;\r
2270                         if (r.getMime()!= null) {\r
2271                                 extension = r.getMime().toLowerCase();\r
2272                                 if (extension.indexOf("/")>-1)\r
2273                                         extension = extension.substring(extension.indexOf("/")+1);\r
2274                         }\r
2275                         String newFile = randint;\r
2276                         if (r.getAttributes().getFileName() != null && r.getAttributes().getFileName() != "")\r
2277                                 if (!locTag.startsWith("src"))\r
2278                                         newFile = newFile+Global.attachmentNameDelimeter+r.getAttributes().getFileName();\r
2279                         r.setNoteGuid(currentNote.getGuid());\r
2280                         \r
2281                         r.setGuid(randint);\r
2282                         conn.getNoteTable().noteResourceTable.saveNoteResource(r, true);\r
2283                                 QFile f = new QFile(Global.getFileManager().getResDirPath(newFile));\r
2284                                 QByteArray bin = new QByteArray(r.getData().getBody());\r
2285                                 f.open(QFile.OpenModeFlag.WriteOnly);\r
2286                                 f.write(bin);\r
2287                                 f.close();\r
2288                                 newSegment = newSegment.replace("guid=\""+guid, "guid=\""+randint);\r
2289                                 currentNote.getResources().add(r);\r
2290                                 \r
2291                                 int startSrcPos = newSegment.indexOf(locTag);\r
2292                                 int endSrcPos = newSegment.indexOf("\"",startSrcPos+locTag.length()+1);\r
2293                                 String source; \r
2294                                 if (locTag.startsWith("src")) {\r
2295                                          source = newSegment.substring(startSrcPos+locTag.length(),endSrcPos);\r
2296                                                 newSegment = newSegment.replace(source,\r
2297                                                         FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath(newFile)));\r
2298                                 } else {\r
2299                                         source = newSegment.substring(startSrcPos+locTag.length(),endSrcPos);\r
2300                                         newSegment = newSegment.replace(source, newFile);\r
2301                                 }\r
2302                                 \r
2303                                 text = text.substring(0,startPos) + newSegment + text.substring(endPos);\r
2304                         }\r
2305                         startPos = text.indexOf(type, startPos+1);\r
2306                 }\r
2307                 return text;\r
2308         }\r
2309 \r
2310 \r
2311         public void nextPage(String file) {\r
2312                 logger.log(logger.EXTREME, "Starting nextPage()");\r
2313                 \r
2314                 Integer pageNumber;\r
2315                 if (previewPageList.containsKey(file))\r
2316                         pageNumber = previewPageList.get(file)+1;\r
2317                 else\r
2318                         pageNumber = 2;\r
2319                 previewPageList.remove(file);\r
2320                 previewPageList.put(file, pageNumber);\r
2321                 PDFPreview pdfPreview = new PDFPreview();\r
2322                 boolean goodPreview = pdfPreview.setupPreview(file, "pdf", pageNumber);\r
2323                 if (goodPreview) {\r
2324 \r
2325 //                      String html = getContent();\r
2326                         QWebSettings.setMaximumPagesInCache(0);\r
2327                         QWebSettings.setObjectCacheCapacities(0, 0, 0);\r
2328 //                      browser.setContent(new QByteArray());\r
2329                         browser.setHtml(browser.page().mainFrame().toHtml());\r
2330                         browser.reload();\r
2331 //                      browser.setContent(new QByteArray(html));\r
2332 //                      browser.triggerPageAction(WebAction.Reload);\r
2333 //                      pdfMouseOver(selectedFile);\r
2334                 }\r
2335         }\r
2336 \r
2337         public void previousPage(String file) {\r
2338                 logger.log(logger.EXTREME, "Starting previousPage()");\r
2339                 \r
2340                 Integer pageNumber;\r
2341                 if (previewPageList.containsKey(file))\r
2342                         pageNumber = previewPageList.get(file)-1;\r
2343                 else\r
2344                         pageNumber = 1;\r
2345                 previewPageList.remove(file);\r
2346                 previewPageList.put(file, pageNumber);\r
2347                 PDFPreview pdfPreview = new PDFPreview();\r
2348                 boolean goodPreview = pdfPreview.setupPreview(file, "pdf", pageNumber);\r
2349                 if (goodPreview) {\r
2350 \r
2351 //                      String html = getContent();\r
2352                         QWebSettings.setMaximumPagesInCache(0);\r
2353                         QWebSettings.setObjectCacheCapacities(0, 0, 0);\r
2354                         browser.setHtml(browser.page().mainFrame().toHtml());\r
2355                         browser.reload();\r
2356 //                      browser.setContent(new QByteArray(html));\r
2357 //                      browser.triggerPageAction(WebAction.Reload);\r
2358                 }\r
2359         }\r
2360         \r
2361 /*      public void pdfMouseOver(String name) { \r
2362                 int pageNumber;\r
2363                 if (previewPageList.containsKey(selectedFile))\r
2364                         pageNumber = previewPageList.get(selectedFile)+1;\r
2365                 else\r
2366                         pageNumber = 1;\r
2367                 \r
2368                 if (pageNumber <= 1)\r
2369                         browser.previousPageAction.setEnabled(false);\r
2370                 else\r
2371                         browser.previousPageAction.setEnabled(true);\r
2372                 \r
2373                 PDFPreview pdf = new PDFPreview();\r
2374                 int totalPages = pdf.getPageCount(name);\r
2375                 if (previewPageList.containsKey(selectedFile))\r
2376                         pageNumber = previewPageList.get(selectedFile)+1;\r
2377                 else\r
2378                         pageNumber = 1;\r
2379                 if (totalPages > pageNumber)\r
2380                         browser.nextPageAction.setEnabled(true);\r
2381                 else\r
2382                         browser.nextPageAction.setEnabled(false);\r
2383         }\r
2384         \r
2385 \r
2386         public void pdfMouseOut() { \r
2387 //              browser.nextPageAction.setVisible(false);\r
2388 //              browser.previousPageAction.setVisible(false);\r
2389         }\r
2390 */\r
2391 }\r