OSDN Git Service

Cleanup compiler warning messages and alter backup & restore to handle new database...
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / xml / NoteFormatter.java
1 package cx.fbn.nevernote.xml;\r
2 \r
3 import java.io.File;\r
4 import java.util.ArrayList;\r
5 import java.util.List;\r
6 \r
7 import com.evernote.edam.type.Note;\r
8 import com.evernote.edam.type.Resource;\r
9 import com.trolltech.qt.core.QByteArray;\r
10 import com.trolltech.qt.core.QDataStream;\r
11 import com.trolltech.qt.core.QFile;\r
12 import com.trolltech.qt.core.QIODevice;\r
13 import com.trolltech.qt.core.QTemporaryFile;\r
14 import com.trolltech.qt.core.QUrl;\r
15 import com.trolltech.qt.xml.QDomAttr;\r
16 import com.trolltech.qt.xml.QDomDocument;\r
17 import com.trolltech.qt.xml.QDomElement;\r
18 import com.trolltech.qt.xml.QDomNodeList;\r
19 \r
20 import cx.fbn.nevernote.Global;\r
21 import cx.fbn.nevernote.config.FileManager;\r
22 import cx.fbn.nevernote.filters.EnSearch;\r
23 import cx.fbn.nevernote.gui.PDFPreview;\r
24 import cx.fbn.nevernote.sql.DatabaseConnection;\r
25 import cx.fbn.nevernote.utilities.ApplicationLogger;\r
26 \r
27 public class NoteFormatter {\r
28 \r
29         private final ApplicationLogger logger;\r
30         private final DatabaseConnection conn;\r
31         public boolean resourceError = false;\r
32         public boolean readOnly = false;\r
33         public boolean addHighlight = true;\r
34         private Note currentNote;\r
35         private String currentNoteGuid;\r
36         private boolean pdfPreview;\r
37         ArrayList<QTemporaryFile> tempFiles;\r
38         private EnSearch enSearch;\r
39         private boolean noteHistory;\r
40         \r
41         public NoteFormatter(ApplicationLogger logger, DatabaseConnection conn, List<QTemporaryFile> tempFiles2) {\r
42                 this.logger = logger;\r
43                 this.conn = conn;\r
44                 noteHistory = false;\r
45         }\r
46         \r
47         \r
48         public void setNote(Note note, boolean pdfPreview) {\r
49                 currentNote = note;\r
50                 this.pdfPreview = pdfPreview;\r
51                 currentNoteGuid = note.getGuid();\r
52                 readOnly = false;\r
53                 resourceError = false;\r
54         }\r
55         \r
56         public void setHighlight(EnSearch search) {\r
57                 if (search==null || search.hilightWords == null ||search.hilightWords.size() == 0) {\r
58                         enSearch = null;\r
59                         addHighlight = false;\r
60                 } else {\r
61                         enSearch = search;\r
62                         addHighlight = true;\r
63                 }\r
64         }\r
65         \r
66         // Set if we are coming here through note histary.  It triggers longer file names to avoid conflicts\r
67         public void setNoteHistory(boolean value) {\r
68                 noteHistory = value;\r
69         }\r
70         \r
71         // Rebuild the note HTML to something usable\r
72         public String rebuildNoteHTML() {\r
73                 logger.log(logger.HIGH, "Entering NeverNote.rebuildNoteHTML");\r
74                 logger.log(logger.EXTREME, "Note guid: " +currentNoteGuid);\r
75                 logger.log(logger.EXTREME, "Note Text:" +currentNote);\r
76                 QDomDocument doc = new QDomDocument();\r
77                 QDomDocument.Result result = doc.setContent(currentNote.getContent());\r
78                 if (!result.success) {\r
79                         logger.log(logger.MEDIUM, "Parse error when rebuilding HTML");\r
80                         logger.log(logger.MEDIUM, "Note guid: " +currentNoteGuid);\r
81                         logger.log(logger.EXTREME, "Start of unmodified note HTML");\r
82                         logger.log(logger.EXTREME, currentNote.getContent());\r
83                         logger.log(logger.EXTREME, "End of unmodified note HTML");\r
84                         return currentNote.getContent();\r
85                 }\r
86 \r
87                 if (tempFiles == null)\r
88                         tempFiles = new ArrayList<QTemporaryFile>();\r
89                 tempFiles.clear();\r
90                 \r
91                 doc = modifyTags(doc);\r
92                 if (addHighlight)\r
93                         doc = addHilight(doc);\r
94                 QDomElement docElem = doc.documentElement();\r
95                 docElem.setTagName("Body");\r
96 //              docElem.setAttribute("bgcolor", "green");\r
97                 logger.log(logger.EXTREME, "Rebuilt HTML:");\r
98                 logger.log(logger.EXTREME, doc.toString());     \r
99                 logger.log(logger.HIGH, "Leaving NeverNote.rebuildNoteHTML");\r
100                 // Fix the stupid problem where inserting an <img> tag after an <a> tag (which is done\r
101                 // to get the <en-media> application tag to work properly) causes spaces to be inserted\r
102                 // between the <a> & <img>.  This messes things up later.  This is an ugly hack.\r
103                 StringBuffer html = new StringBuffer(doc.toString());\r
104                 for (int i=html.indexOf("<a en-tag=\"en-media\" ", 0); i>-1; i=html.indexOf("<a en-tag=\"en-media\" ", i)) {\r
105                         i=html.indexOf(">\n",i+1);\r
106                         int z = html.indexOf("<img",i);\r
107                         for (int j=z-1; j>i; j--) \r
108                                 html.deleteCharAt(j);\r
109                         i=html.indexOf("/>", z+1);\r
110                         z = html.indexOf("</a>",i);\r
111                         for (int j=z-1; j>i+1; j--) \r
112                                 html.deleteCharAt(j);\r
113                 } \r
114                 return html.toString();\r
115         }       \r
116 \r
117         \r
118     // Modify the en-media tag into an image tag so it can be displayed.\r
119     private void modifyImageTags(QDomElement docElem, QDomElement enmedia, QDomAttr hash) {\r
120         logger.log(logger.HIGH, "Entering NeverNote.modifyImageTags");\r
121         String type = enmedia.attribute("type");\r
122         if (type.startsWith("image/"))\r
123                 type = "."+type.substring(6);\r
124         else\r
125                 type="";\r
126         \r
127         String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNoteGuid, hash.value());\r
128         QFile tfile = new QFile(Global.getFileManager().getResDirPath(resGuid + type));\r
129         if (!tfile.exists()) {\r
130                 Resource r = null;\r
131                 if (resGuid != null)\r
132                         r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid,true);\r
133                         if (r==null || r.getData() == null || r.getData().getBody().length == 0)\r
134                                 resourceError = true;;\r
135                         if (r!= null && r.getData() != null && r.getData().getBody().length > 0) {\r
136                                 tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));\r
137                                 QByteArray binData = new QByteArray(r.getData().getBody());\r
138                                 tfile.write(binData);\r
139                                 tfile.close();\r
140                                 enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());\r
141                                 enmedia.setAttribute("en-tag", "en-media");\r
142                                 enmedia.setNodeValue("");\r
143                         enmedia.setAttribute("guid", r.getGuid());\r
144                         enmedia.setTagName("img");\r
145                 }\r
146         }\r
147         // Technically, we should do a file:// to have a proper url, but for some reason QWebPage hates\r
148         // them and won't generate a thumbnail image properly if we use them.\r
149 //              enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());\r
150                 enmedia.setAttribute("src", tfile.fileName().toString());\r
151                 enmedia.setAttribute("en-tag", "en-media");\r
152                 enmedia.setAttribute("onContextMenu", "window.jambi.imageContextMenu('" +tfile.fileName()  +"');");\r
153                 enmedia.setNodeValue("");\r
154                 enmedia.setAttribute("guid", resGuid);\r
155                 enmedia.setTagName("img");\r
156 \r
157                 logger.log(logger.HIGH, "Leaving NeverNote.modifyImageTags");\r
158     }\r
159     \r
160     \r
161         // Modify tags from Evernote specific things to XHTML tags.\r
162         private QDomDocument modifyTags(QDomDocument doc) {\r
163                 logger.log(logger.HIGH, "Entering NeverNote.modifyTags");\r
164                 if (tempFiles == null)\r
165                         tempFiles = new ArrayList<QTemporaryFile>();\r
166                 tempFiles.clear();\r
167                 QDomElement docElem = doc.documentElement();\r
168                 \r
169                 // Modify en-media tags\r
170                 QDomNodeList anchors = docElem.elementsByTagName("en-media");\r
171                 int enMediaCount = anchors.length();\r
172                 for (int i=enMediaCount-1; i>=0; i--) {\r
173                         QDomElement enmedia = anchors.at(i).toElement();\r
174                         if (enmedia.hasAttribute("type")) {\r
175                                 QDomAttr attr = enmedia.attributeNode("type");\r
176                                 QDomAttr hash = enmedia.attributeNode("hash");\r
177                                 String[] type = attr.nodeValue().split("/");\r
178                                 String appl = type[1];\r
179                                 \r
180                                 if (type[0] != null) {\r
181                                         if (type[0].equals("image")) {\r
182                                                 modifyImageTags(docElem, enmedia, hash);\r
183                                         }\r
184                                         if (!type[0].equals("image")) {\r
185                                                 modifyApplicationTags(doc, docElem, enmedia, hash, appl);\r
186                                         }\r
187                                 }\r
188                         }\r
189                 }\r
190                 \r
191                 // Modify todo tags\r
192                 anchors = docElem.elementsByTagName("en-todo");\r
193                 int enTodoCount = anchors.length();\r
194                 for (int i=enTodoCount-1; i>=0; i--) {\r
195                         QDomElement enmedia = anchors.at(i).toElement();\r
196                         modifyTodoTags(enmedia);\r
197                 }\r
198                 \r
199                 // Modify en-crypt tags\r
200                 anchors = docElem.elementsByTagName("en-crypt");\r
201                 int enCryptLen = anchors.length();\r
202                 for (int i=enCryptLen-1; i>=0; i--) {\r
203                         QDomElement enmedia = anchors.at(i).toElement();\r
204                         enmedia.setAttribute("contentEditable","false");\r
205                         enmedia.setAttribute("src", Global.getFileManager().getImageDirPath("encrypt.png"));\r
206                         enmedia.setAttribute("en-tag","en-crypt");\r
207                         enmedia.setAttribute("alt", enmedia.text());\r
208                         Global.cryptCounter++;\r
209                         enmedia.setAttribute("id", "crypt"+Global.cryptCounter.toString());\r
210                         String encryptedText = enmedia.text();\r
211                         \r
212                         // If the encryption string contains crlf at the end, remove them because they mess up the javascript.\r
213                         if (encryptedText.endsWith("\n"))\r
214                                 encryptedText = encryptedText.substring(0,encryptedText.length()-1);\r
215                         if (encryptedText.endsWith("\r"))\r
216                                 encryptedText = encryptedText.substring(0,encryptedText.length()-1);\r
217                         \r
218                         // Add the commands\r
219                         String hint = enmedia.attribute("hint");\r
220                         hint = hint.replace("'","&apos;");\r
221                         enmedia.setAttribute("onClick", "window.jambi.decryptText('crypt"+Global.cryptCounter.toString()+"', '"+encryptedText+"', '"+hint+"');");\r
222                         enmedia.setAttribute("onMouseOver", "style.cursor='hand'");\r
223                         enmedia.setTagName("img");\r
224                         enmedia.removeChild(enmedia.firstChild());   // Remove the actual encrypted text\r
225                 }\r
226 \r
227                 \r
228                 // Modify link tags\r
229                 anchors = docElem.elementsByTagName("a");\r
230                 enCryptLen = anchors.length();\r
231                 for (int i=0; i<anchors.length(); i++) {\r
232                         QDomElement element = anchors.at(i).toElement();\r
233                         element.setAttribute("title", element.attribute("href"));\r
234                 }\r
235 \r
236                 logger.log(logger.HIGH, "Leaving NeverNote.modifyTags");\r
237                 return doc;\r
238         }\r
239         \r
240         \r
241     // Modify the en-media tag into an attachment\r
242     private void modifyApplicationTags(QDomDocument doc, QDomElement docElem, QDomElement enmedia, QDomAttr hash, String appl) {\r
243         logger.log(logger.HIGH, "Entering NeverNote.modifyApplicationTags");\r
244         if (appl.equalsIgnoreCase("vnd.evernote.ink"))\r
245                 readOnly = true;\r
246         String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNote.getGuid(), hash.value());\r
247         Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid, false);\r
248         if (r == null || r.getData() == null) \r
249                 resourceError = true;\r
250                 if (r!= null) {\r
251                         if (r.getData()!=null) {\r
252                                 // Did we get a generic applicaiton?  Then look at the file name to \r
253                                 // try and find a good application type for the icon\r
254                                 if (appl.equalsIgnoreCase("octet-stream")) {\r
255                                         if (r.getAttributes() != null && r.getAttributes().getFileName() != null) {\r
256                                                 String fn = r.getAttributes().getFileName();\r
257                                                 int pos = fn.lastIndexOf(".");\r
258                                                 if (pos > -1) {\r
259                                                         appl = fn.substring(pos+1);\r
260                                                 }\r
261                                         }\r
262                                 }\r
263                                 \r
264                                 String fileDetails = null;\r
265                                 if (r.getAttributes() != null && r.getAttributes().getFileName() != null && !r.getAttributes().getFileName().equals(""))\r
266                                         fileDetails = r.getAttributes().getFileName();\r
267                                 String contextFileName;\r
268                                 FileManager fileManager = Global.getFileManager();\r
269                 if (fileDetails != null && !fileDetails.equals("")) {\r
270                         if (!noteHistory) {\r
271                                 enmedia.setAttribute("href", "nnres://" +r.getGuid() \r
272                                                 +Global.attachmentNameDelimeter +fileDetails);\r
273                                 contextFileName = fileManager.getResDirPath(r.getGuid() \r
274                                                 +Global.attachmentNameDelimeter + fileDetails);\r
275                         } else {\r
276                                 enmedia.setAttribute("href", "nnres://" +r.getGuid() + currentNote.getUpdateSequenceNum() \r
277                                                 +Global.attachmentNameDelimeter +fileDetails);\r
278                                 contextFileName = fileManager.getResDirPath(r.getGuid() + currentNote.getUpdateSequenceNum() \r
279                                                 +Global.attachmentNameDelimeter + fileDetails);\r
280                         }\r
281                                 } else { \r
282                                         if (!noteHistory) {\r
283                                                 enmedia.setAttribute("href", "nnres://" +r.getGuid() +currentNote.getUpdateSequenceNum()\r
284                                                                 +Global.attachmentNameDelimeter +appl);\r
285                                                 contextFileName = fileManager.getResDirPath(r.getGuid() +currentNote.getUpdateSequenceNum() \r
286                                                                 +Global.attachmentNameDelimeter + appl);\r
287                                         } else {\r
288                                                 enmedia.setAttribute("href", "nnres://" +r.getGuid() \r
289                                                                 +Global.attachmentNameDelimeter +appl);\r
290                                                 contextFileName = fileManager.getResDirPath(r.getGuid() \r
291                                                                 +Global.attachmentNameDelimeter + appl);\r
292                                         }\r
293                                 }\r
294                                 contextFileName = contextFileName.replace("\\", "/");\r
295                                 enmedia.setAttribute("onContextMenu", "window.jambi.resourceContextMenu('" +contextFileName +"');");\r
296                                 if (fileDetails == null || fileDetails.equals(""))\r
297                                         fileDetails = "";\r
298                                 enmedia.setAttribute("en-tag", "en-media");\r
299                                 enmedia.setAttribute("guid", r.getGuid());\r
300                                 enmedia.setTagName("a");\r
301                                 QDomElement newText = doc.createElement("img");\r
302                                 boolean goodPreview = false;\r
303                                 String filePath = "";\r
304                                 if (appl.equalsIgnoreCase("pdf") && pdfPreview) {\r
305                                         String fileName;\r
306                                         Resource res = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);\r
307                                         if (res.getAttributes() != null && \r
308                                                         res.getAttributes().getFileName() != null && \r
309                                                         !res.getAttributes().getFileName().trim().equals(""))\r
310                                                 fileName = res.getGuid()+Global.attachmentNameDelimeter+res.getAttributes().getFileName();\r
311                                         else\r
312                                                 fileName = res.getGuid()+".pdf";\r
313                                         QFile file = new QFile(fileManager.getResDirPath(fileName));\r
314                                 QFile.OpenMode mode = new QFile.OpenMode();\r
315                                 mode.set(QFile.OpenModeFlag.WriteOnly);\r
316                                 file.open(mode);\r
317                                 QDataStream out = new QDataStream(file);\r
318                                 Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(res.getGuid(), true);\r
319                                         QByteArray binData = new QByteArray(resBinary.getData().getBody());\r
320                                         resBinary = null;\r
321                                 out.writeBytes(binData.toByteArray());\r
322                                 file.close();\r
323                                 PDFPreview pdfPreview = new PDFPreview();\r
324                                         goodPreview = pdfPreview.setupPreview(file.fileName(), appl,0);\r
325                                         if (goodPreview) {\r
326                                                 QDomElement span = doc.createElement("span");\r
327                                                 QDomElement table = doc.createElement("table");\r
328                                                 span.setAttribute("pdfNavigationTable", "true");\r
329                                                 QDomElement tr = doc.createElement("tr");\r
330                                                 QDomElement td = doc.createElement("td");\r
331                                                 QDomElement left = doc.createElement("img");\r
332                                                 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");\r
333                                                 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");\r
334                                                 left.setAttribute("onMouseOver", "style.cursor='hand'");\r
335                                                 QDomElement right = doc.createElement("img");\r
336                                                 right.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");\r
337                                                 left.setAttribute("onMouseDown", "window.jambi.previousPage('" +file.fileName() +"')");\r
338                                                 // NFC TODO: should these be file:// URLs?\r
339                                                 left.setAttribute("src", Global.getFileManager().getImageDirPath("small_left.png"));\r
340                                                 right.setAttribute("src", Global.getFileManager().getImageDirPath("small_right.png"));\r
341                                                 right.setAttribute("onMouseOver", "style.cursor='hand'");\r
342                                                 \r
343                                                 table.appendChild(tr);\r
344                                                 tr.appendChild(td);\r
345                                                 td.appendChild(left);\r
346                                                 td.appendChild(right);\r
347                                                 span.appendChild(table);\r
348                                                 enmedia.parentNode().insertBefore(span, enmedia);\r
349                                         } \r
350                                         filePath = fileName+".png";\r
351                                 }\r
352                                 String icon = findIcon(appl);\r
353                                 if (icon.equals("attachment.png"))\r
354                                         icon = findIcon(fileDetails.substring(fileDetails.indexOf(".")+1));\r
355                                 // NFC TODO: should this be a 'file://' URL?\r
356                                 newText.setAttribute("src", Global.getFileManager().getImageDirPath(icon));\r
357                                 if (goodPreview) {\r
358                                 // NFC TODO: should this be a 'file://' URL?\r
359                                         newText.setAttribute("src", fileManager.getResDirPath(filePath));\r
360                                         newText.setAttribute("style", "border-style:solid; border-color:green; padding:0.5mm 0.5mm 0.5mm 0.5mm;");\r
361                                 }\r
362                                 newText.setAttribute("title", fileDetails);\r
363                                 enmedia.removeChild(enmedia.firstChild());\r
364                                 \r
365                                 enmedia.appendChild(newText);\r
366                         }\r
367                 }\r
368                 logger.log(logger.HIGH, "Leaving NeverNote.modifyApplicationTags");\r
369     }\r
370     // Modify the en-to tag into an input field\r
371     private void modifyTodoTags(QDomElement todo) {\r
372         logger.log(logger.HIGH, "Entering NeverNote.modifyTodoTags");\r
373                 todo.setAttribute("type", "checkbox");\r
374                 String checked = todo.attribute("checked");\r
375                 todo.removeAttribute("checked");\r
376                 if (checked.equalsIgnoreCase("true"))\r
377                         todo.setAttribute("checked", "");\r
378                 else\r
379                         todo.setAttribute("unchecked","");\r
380                 todo.setAttribute("value", checked);\r
381                 todo.setAttribute("onClick", "value=checked;window.jambi.contentChanged(); ");\r
382                 todo.setTagName("input");\r
383                 logger.log(logger.HIGH, "Leaving NeverNote.modifyTodoTags");\r
384     }\r
385     \r
386     \r
387     \r
388     // Modify any cached todo tags that may have changed\r
389     public String modifyCachedTodoTags(String note) {\r
390         logger.log(logger.HIGH, "Entering NeverNote.modifyCachedTodoTags");\r
391         StringBuffer html = new StringBuffer(note);\r
392                 for (int i=html.indexOf("<input", 0); i>-1; i=html.indexOf("<input", i)) {\r
393                         int endPos =html.indexOf(">",i+1);\r
394                         String input = html.substring(i,endPos);\r
395                         if (input.indexOf("value=\"true\"") > 0) \r
396                                 input = input.replace(" unchecked=\"\"", " checked=\"\"");\r
397                         else\r
398                                 input = input.replace(" checked=\"\"", " unchecked=\"\"");\r
399                         html.replace(i, endPos, input);\r
400                         i++;\r
401                 }\r
402                 logger.log(logger.HIGH, "Leaving NeverNote.modifyCachedTodoTags");\r
403                 return html.toString();\r
404     }\r
405     \r
406     \r
407 \r
408 \r
409         // Scan and do hilighting of words\r
410         public QDomDocument addHilight(QDomDocument doc) {\r
411 //              EnSearch e = listManager.getEnSearch();\r
412                 if (enSearch.hilightWords == null || enSearch.hilightWords.size() == 0)\r
413                         return doc;\r
414                 XMLInsertHilight hilight = new XMLInsertHilight(doc, enSearch.hilightWords);\r
415                 return hilight.getDoc();\r
416         }\r
417         \r
418         \r
419     // find the appropriate icon for an attachment\r
420     private String findIcon(String appl) {\r
421         logger.log(logger.HIGH, "Entering NeverNote.findIcon");\r
422         appl = appl.toLowerCase();\r
423         String relativePath = appl + ".png";\r
424         File f = Global.getFileManager().getImageDirFile(relativePath);\r
425         if (f.exists()) {\r
426             return relativePath;\r
427         }\r
428         if (f.exists())\r
429                 return appl+".png";\r
430         logger.log(logger.HIGH, "Leaving NeverNote.findIcon");\r
431         return "attachment.png";\r
432     }\r
433 \r
434 \r
435 }\r