OSDN Git Service

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