]> git.lyx.org Git - lyx.git/blob - src/VCBackend.cpp
208161bb24a928eed815748e483273d951c5b2ae
[lyx.git] / src / VCBackend.cpp
1 /**
2  * \file VCBackend.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Pavel Sanda
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "VCBackend.h"
15 #include "Buffer.h"
16 #include "LyX.h"
17 #include "FuncRequest.h"
18
19 #include "frontends/alert.h"
20 #include "frontends/Application.h"
21
22 #include "support/convert.h"
23 #include "support/debug.h"
24 #include "support/filetools.h"
25 #include "support/gettext.h"
26 #include "support/lstrings.h"
27 #include "support/Path.h"
28 #include "support/Systemcall.h"
29 #include "support/regex.h"
30
31 #include <fstream>
32
33 using namespace std;
34 using namespace lyx::support;
35
36
37
38 namespace lyx {
39
40
41 int VCS::doVCCommandCall(string const & cmd, FileName const & path)
42 {
43         LYXERR(Debug::LYXVC, "doVCCommandCall: " << cmd);
44         Systemcall one;
45         support::PathChanger p(path);
46         return one.startscript(Systemcall::Wait, cmd, false);
47 }
48
49
50 int VCS::doVCCommand(string const & cmd, FileName const & path, bool reportError)
51 {
52         if (owner_)
53                 owner_->setBusy(true);
54
55         int const ret = doVCCommandCall(cmd, path);
56
57         if (owner_)
58                 owner_->setBusy(false);
59         if (ret && reportError)
60                 frontend::Alert::error(_("Revision control error."),
61                         bformat(_("Some problem occured while running the command:\n"
62                                   "'%1$s'."),
63                         from_utf8(cmd)));
64         return ret;
65 }
66
67
68 /////////////////////////////////////////////////////////////////////
69 //
70 // RCS
71 //
72 /////////////////////////////////////////////////////////////////////
73
74 RCS::RCS(FileName const & m)
75 {
76         master_ = m;
77         scanMaster();
78 }
79
80
81 FileName const RCS::findFile(FileName const & file)
82 {
83         // Check if *,v exists.
84         FileName tmp(file.absFileName() + ",v");
85         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under rcs: " << tmp);
86         if (tmp.isReadableFile()) {
87                 LYXERR(Debug::LYXVC, "Yes, " << file << " is under rcs.");
88                 return tmp;
89         }
90
91         // Check if RCS/*,v exists.
92         tmp = FileName(addName(addPath(onlyPath(file.absFileName()), "RCS"), file.absFileName()) + ",v");
93         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under rcs: " << tmp);
94         if (tmp.isReadableFile()) {
95                 LYXERR(Debug::LYXVC, "Yes, " << file << " is under rcs.");
96                 return tmp;
97         }
98
99         return FileName();
100 }
101
102
103 void RCS::retrieve(FileName const & file)
104 {
105         LYXERR(Debug::LYXVC, "LyXVC::RCS: retrieve.\n\t" << file);
106         doVCCommandCall("co -q -r " + quoteName(file.toFilesystemEncoding()),
107                          FileName());
108 }
109
110
111 void RCS::scanMaster()
112 {
113         if (master_.empty())
114                 return;
115
116         LYXERR(Debug::LYXVC, "LyXVC::RCS: scanMaster: " << master_);
117
118         ifstream ifs(master_.toFilesystemEncoding().c_str());
119
120         string token;
121         bool read_enough = false;
122
123         while (!read_enough && ifs >> token) {
124                 LYXERR(Debug::LYXVC, "LyXVC::scanMaster: current lex text: `"
125                         << token << '\'');
126
127                 if (token.empty())
128                         continue;
129                 else if (token == "head") {
130                         // get version here
131                         string tmv;
132                         ifs >> tmv;
133                         tmv = rtrim(tmv, ";");
134                         version_ = tmv;
135                         LYXERR(Debug::LYXVC, "LyXVC: version found to be " << tmv);
136                 } else if (contains(token, "access")
137                            || contains(token, "symbols")
138                            || contains(token, "strict")) {
139                         // nothing
140                 } else if (contains(token, "locks")) {
141                         // get locker here
142                         if (contains(token, ';')) {
143                                 locker_ = "Unlocked";
144                                 vcstatus = UNLOCKED;
145                                 continue;
146                         }
147                         string tmpt;
148                         string s1;
149                         string s2;
150                         do {
151                                 ifs >> tmpt;
152                                 s1 = rtrim(tmpt, ";");
153                                 // tmp is now in the format <user>:<version>
154                                 s1 = split(s1, s2, ':');
155                                 // s2 is user, and s1 is version
156                                 if (s1 == version_) {
157                                         locker_ = s2;
158                                         vcstatus = LOCKED;
159                                         break;
160                                 }
161                         } while (!contains(tmpt, ';'));
162
163                 } else if (token == "comment") {
164                         // we don't need to read any further than this.
165                         read_enough = true;
166                 } else {
167                         // unexpected
168                         LYXERR(Debug::LYXVC, "LyXVC::scanMaster(): unexpected token");
169                 }
170         }
171 }
172
173
174 void RCS::registrer(string const & msg)
175 {
176         string cmd = "ci -q -u -i -t-\"";
177         cmd += msg;
178         cmd += "\" ";
179         cmd += quoteName(onlyFileName(owner_->absFileName()));
180         doVCCommand(cmd, FileName(owner_->filePath()));
181 }
182
183
184 string RCS::checkIn(string const & msg)
185 {
186         int ret = doVCCommand("ci -q -u -m\"" + msg + "\" "
187                     + quoteName(onlyFileName(owner_->absFileName())),
188                     FileName(owner_->filePath()));
189         return ret ? string() : "RCS: Proceeded";
190 }
191
192
193 bool RCS::checkInEnabled()
194 {
195         return owner_ && !owner_->isReadonly();
196 }
197
198
199 string RCS::checkOut()
200 {
201         owner_->markClean();
202         int ret = doVCCommand("co -q -l " + quoteName(onlyFileName(owner_->absFileName())),
203                     FileName(owner_->filePath()));
204         return ret ? string() : "RCS: Proceeded";
205 }
206
207
208 bool RCS::checkOutEnabled()
209 {
210         return owner_ && owner_->isReadonly();
211 }
212
213
214 string RCS::repoUpdate()
215 {
216         lyxerr << "Sorry, not implemented." << endl;
217         return string();
218 }
219
220
221 bool RCS::repoUpdateEnabled()
222 {
223         return false;
224 }
225
226
227 string RCS::lockingToggle()
228 {
229         lyxerr << "Sorry, not implemented." << endl;
230         return string();
231 }
232
233
234 bool RCS::lockingToggleEnabled()
235 {
236         return false;
237 }
238
239
240 void RCS::revert()
241 {
242         doVCCommand("co -f -u" + version_ + " "
243                     + quoteName(onlyFileName(owner_->absFileName())),
244                     FileName(owner_->filePath()));
245         // We ignore changes and just reload!
246         owner_->markClean();
247 }
248
249
250 void RCS::undoLast()
251 {
252         LYXERR(Debug::LYXVC, "LyXVC: undoLast");
253         doVCCommand("rcs -o" + version_ + " "
254                     + quoteName(onlyFileName(owner_->absFileName())),
255                     FileName(owner_->filePath()));
256 }
257
258
259 bool RCS::undoLastEnabled()
260 {
261         return true;
262 }
263
264
265 void RCS::getLog(FileName const & tmpf)
266 {
267         doVCCommand("rlog " + quoteName(onlyFileName(owner_->absFileName()))
268                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
269                     FileName(owner_->filePath()));
270 }
271
272
273 bool RCS::toggleReadOnlyEnabled()
274 {
275         // This got broken somewhere along lfuns dispatch reorganization.
276         // reloadBuffer would be needed after this, but thats problematic
277         // since we are inside Buffer::dispatch.
278         // return true;
279         return false;
280 }
281
282 string RCS::revisionInfo(LyXVC::RevisionInfo const info)
283 {
284         if (info == LyXVC::File)
285                 return version_;
286         return string();
287 }
288
289
290 bool RCS::prepareFileRevision(string const &revis, string & f)
291 {
292         string rev = revis;
293
294         if (isStrInt(rev)) {
295                 int back = convert<int>(rev);
296                 // if positive use as the last number in the whole revision string
297                 if (back > 0) {
298                         string base;
299                         rsplit(version_, base , '.' );
300                         rev = base + "." + rev;
301                 }
302                 if (back == 0)
303                         rev = version_;
304                 // we care about the last number from revision string
305                 // in case of backward indexing
306                 if (back < 0) {
307                         string cur, base;
308                         cur = rsplit(version_, base , '.' );
309                         if (!isStrInt(cur))
310                                 return false;
311                         int want = convert<int>(cur) + back;
312                         if (want <= 0)
313                                 return false;
314
315                         rev = base + "." + convert<string>(want);
316                 }
317         }
318
319         FileName tmpf = FileName::tempName("lyxvcrev_" + rev + "_");
320         if (tmpf.empty()) {
321                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
322                 return N_("Error: Could not generate logfile.");
323         }
324
325         doVCCommand("co -p" + rev + " "
326                       + quoteName(onlyFileName(owner_->absFileName()))
327                       + " > " + quoteName(tmpf.toFilesystemEncoding()),
328                 FileName(owner_->filePath()));
329         if (tmpf.isFileEmpty())
330                 return false;
331
332         f = tmpf.absFileName();
333         return true;
334 }
335
336
337 bool RCS::prepareFileRevisionEnabled()
338 {
339         return true;
340 }
341
342
343 /////////////////////////////////////////////////////////////////////
344 //
345 // CVS
346 //
347 /////////////////////////////////////////////////////////////////////
348
349 CVS::CVS(FileName const & m, FileName const & f)
350 {
351         master_ = m;
352         file_ = f;
353         scanMaster();
354 }
355
356
357 FileName const CVS::findFile(FileName const & file)
358 {
359         // First we look for the CVS/Entries in the same dir
360         // where we have file.
361         FileName const entries(onlyPath(file.absFileName()) + "/CVS/Entries");
362         string const tmpf = '/' + onlyFileName(file.absFileName()) + '/';
363         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under cvs in `" << entries
364                              << "' for `" << tmpf << '\'');
365         if (entries.isReadableFile()) {
366                 // Ok we are at least in a CVS dir. Parse the CVS/Entries
367                 // and see if we can find this file. We do a fast and
368                 // dirty parse here.
369                 ifstream ifs(entries.toFilesystemEncoding().c_str());
370                 string line;
371                 while (getline(ifs, line)) {
372                         LYXERR(Debug::LYXVC, "\tEntries: " << line);
373                         if (contains(line, tmpf))
374                                 return entries;
375                 }
376         }
377         return FileName();
378 }
379
380
381 void CVS::scanMaster()
382 {
383         LYXERR(Debug::LYXVC, "LyXVC::CVS: scanMaster. \n     Checking: " << master_);
384         // Ok now we do the real scan...
385         ifstream ifs(master_.toFilesystemEncoding().c_str());
386         string name = onlyFileName(file_.absFileName());
387         string tmpf = '/' + name + '/';
388         LYXERR(Debug::LYXVC, "\tlooking for `" << tmpf << '\'');
389         string line;
390         static regex const reg("/(.*)/(.*)/(.*)/(.*)/(.*)");
391         while (getline(ifs, line)) {
392                 LYXERR(Debug::LYXVC, "\t  line: " << line);
393                 if (contains(line, tmpf)) {
394                         // Ok extract the fields.
395                         smatch sm;
396
397                         regex_match(line, sm, reg);
398
399                         //sm[0]; // whole matched string
400                         //sm[1]; // filename
401                         version_ = sm.str(2);
402                         string const file_date = sm.str(3);
403
404                         //sm[4]; // options
405                         //sm[5]; // tag or tagdate
406                         if (file_.isReadableFile()) {
407                                 time_t mod = file_.lastModified();
408                                 string mod_date = rtrim(asctime(gmtime(&mod)), "\n");
409                                 LYXERR(Debug::LYXVC, "Date in Entries: `" << file_date
410                                         << "'\nModification date of file: `" << mod_date << '\'');
411                                 if (file_.isReadOnly()) {
412                                         // readonly checkout is unlocked
413                                         vcstatus = UNLOCKED;
414                                 } else {
415                                         FileName bdir(addPath(master_.onlyPath().absFileName(),"Base"));
416                                         FileName base(addName(bdir.absFileName(),name));
417                                         // if base version is existent "cvs edit" was used to lock
418                                         vcstatus = base.isReadableFile() ? LOCKED : NOLOCKING;
419                                 }
420                         } else {
421                                 vcstatus = NOLOCKING;
422                         }
423                         break;
424                 }
425         }
426 }
427
428
429 string const CVS::getTarget(OperationMode opmode) const
430 {
431         switch(opmode) {
432         case Directory:
433                 return quoteName(owner_->filePath());
434         case File:
435                 return quoteName(onlyFileName(owner_->absFileName()));
436         }
437         return string();
438 }
439
440
441 docstring CVS::toString(CvsStatus status) const
442 {
443         switch (status) {
444         case UpToDate:
445                 return _("Up-to-date");
446         case LocallyModified:
447                 return _("Locally Modified");
448         case LocallyAdded:
449                 return _("Locally Added");
450         case NeedsMerge:
451                 return _("Needs Merge");
452         case NeedsCheckout:
453                 return _("Needs Checkout");
454         case NoCvsFile:
455                 return _("No CVS file");
456         case StatusError:
457                 return _("Cannot retrieve CVS status");
458         }
459         return 0;
460 }
461
462
463 CVS::CvsStatus CVS::getStatus()
464 {
465         FileName tmpf = FileName::tempName("lyxvcout");
466         if (tmpf.empty()) {
467                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
468                 return StatusError;
469         }
470
471         if (doVCCommand("cvs status " + getTarget(File)
472                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
473                 FileName(owner_->filePath()))) {
474                 tmpf.removeFile();
475                 return StatusError;
476         }
477
478         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
479         CvsStatus status = NoCvsFile;
480
481         while (ifs) {
482                 string line;
483                 getline(ifs, line);
484                 LYXERR(Debug::LYXVC, line << "\n");
485                 if (prefixIs(line, "File:")) {
486                         if (contains(line, "Up-to-date"))
487                                 status = UpToDate;
488                         else if (contains(line, "Locally Modified"))
489                                 status = LocallyModified;
490                         else if (contains(line, "Locally Added"))
491                                 status = LocallyAdded;
492                         else if (contains(line, "Needs Merge"))
493                                 status = NeedsMerge;
494                         else if (contains(line, "Needs Checkout"))
495                                 status = NeedsCheckout;
496                 }
497         }
498         tmpf.removeFile();
499         return status;
500 }
501
502
503 void CVS::registrer(string const & msg)
504 {
505         doVCCommand("cvs -q add -m \"" + msg + "\" "
506                 + getTarget(File),
507                 FileName(owner_->filePath()));
508 }
509
510
511 void CVS::getDiff(OperationMode opmode, FileName const & tmpf)
512 {
513         doVCCommand("cvs diff " + getTarget(opmode)
514                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
515                 FileName(owner_->filePath()), false);
516 }
517
518
519 int CVS::edit()
520 {
521         vcstatus = LOCKED;
522         return doVCCommand("cvs -q edit " + getTarget(File),
523                 FileName(owner_->filePath()));
524 }
525
526
527 int CVS::unedit()
528 {
529         vcstatus = UNLOCKED;
530         return doVCCommand("cvs -q unedit " + getTarget(File),
531                 FileName(owner_->filePath()));
532 }
533
534
535 int CVS::update(OperationMode opmode, FileName const & tmpf)
536 {
537         string const redirection = tmpf.empty() ? ""
538                 : " > " + quoteName(tmpf.toFilesystemEncoding());
539
540         return doVCCommand("cvs -q update "
541                 + getTarget(opmode) + redirection,
542                 FileName(owner_->filePath()));
543 }
544
545
546 string CVS::scanLogFile(FileName const & f, string & status)
547 {
548         ifstream ifs(f.toFilesystemEncoding().c_str());
549
550         while (ifs) {
551                 string line;
552                 getline(ifs, line);
553                 LYXERR(Debug::LYXVC, line << "\n");
554                 if (!line.empty())
555                         status += line + "; ";
556                 if (prefixIs(line, "C ")) {
557                         ifs.close();
558                         return line;
559                 }
560         }
561         ifs.close();
562         return string();
563 }
564         
565         
566 string CVS::checkIn(string const & msg)
567 {
568         CvsStatus status = getStatus();
569         switch (status) {
570         case UpToDate:
571                 if (vcstatus != NOLOCKING)
572                         unedit();
573                 return "CVS: Proceeded";
574         case LocallyModified:
575         case LocallyAdded: {
576                 int rc = doVCCommand("cvs -q commit -m \"" + msg + "\" "
577                         + getTarget(File),
578                     FileName(owner_->filePath()));
579                 return rc ? string() : "CVS: Proceeded";
580         }
581         case NeedsMerge:
582         case NeedsCheckout:
583                 frontend::Alert::error(_("Revision control error."),
584                         _("The repository version is newer then the current check out.\n"
585                           "You have to update from repository first or revert your changes.")) ;
586                 break;
587         default:
588                 frontend::Alert::error(_("Revision control error."),
589                         bformat(_("Bad status when checking in changes.\n"
590                                           "\n'%1$s'\n\n"),
591                                 toString(status)));
592                 break;
593         }
594         return string();
595 }
596
597
598 bool CVS::isLocked() const
599 {
600         FileName fn(owner_->absFileName());
601         fn.refresh();
602         return !fn.isReadOnly();
603 }
604
605
606 bool CVS::checkInEnabled()
607 {
608         if (vcstatus != NOLOCKING)
609                 return isLocked();
610         else
611                 return true;
612 }
613
614
615 string CVS::checkOut()
616 {
617         if (vcstatus != NOLOCKING && edit())
618                 return string();
619         FileName tmpf = FileName::tempName("lyxvcout");
620         if (tmpf.empty()) {
621                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
622                 return string();
623         }
624         
625         int rc = update(File, tmpf);
626         string log;
627         string const res = scanLogFile(tmpf, log);
628         if (!res.empty())
629                 frontend::Alert::error(_("Revision control error."),
630                         bformat(_("Error when updating from repository.\n"
631                                 "You have to manually resolve the conflicts NOW!\n'%1$s'.\n\n"
632                                 "After pressing OK, LyX will try to reopen the resolved document."),
633                                 from_local8bit(res)));
634         
635         tmpf.erase();
636         return rc ? string() : log.empty() ? "CVS: Proceeded" : "CVS: " + log;
637 }
638
639
640 bool CVS::checkOutEnabled()
641 {
642         if (vcstatus != NOLOCKING)
643                 return !isLocked();
644         else
645                 return true;
646 }
647
648
649 string CVS::repoUpdate()
650 {
651         FileName tmpf = FileName::tempName("lyxvcout");
652         if (tmpf.empty()) {
653                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
654                 return string();
655         }
656         
657         getDiff(Directory, tmpf);
658         docstring res = tmpf.fileContents("UTF-8");
659         if (!res.empty()) {
660                 LYXERR(Debug::LYXVC, "Diff detected:\n" << res);
661                 docstring const file = from_utf8(owner_->filePath());
662                 docstring text = bformat(_("There were detected changes "
663                                 "in the working directory:\n%1$s\n\n"
664                                 "In case of file conflict you have to resolve them "
665                                 "manually or revert to repository version later."), file);
666                 int ret = frontend::Alert::prompt(_("Changes detected"),
667                                 text, 0, 1, _("&Continue"), _("&Abort"), _("View &Log ..."));
668                 if (ret == 2 ) {
669                         dispatch(FuncRequest(LFUN_DIALOG_SHOW, "file " + tmpf.absFileName()));
670                         ret = frontend::Alert::prompt(_("Changes detected"),
671                                 text, 0, 1, _("&Continue"), _("&Abort"));
672                         hideDialogs("file", 0);
673                 }
674                 if (ret == 1 ) {
675                         tmpf.removeFile();
676                         return string();
677                 }
678         }
679
680         int rc = update(Directory, tmpf);
681         res += "Update log:\n" + tmpf.fileContents("UTF-8");
682         tmpf.removeFile();
683
684         LYXERR(Debug::LYXVC, res);
685         return rc ? string() : "CVS: Proceeded" ;
686 }
687
688
689 bool CVS::repoUpdateEnabled()
690 {
691         return true;
692 }
693
694
695 string CVS::lockingToggle()
696 {
697         lyxerr << "Sorry, not implemented." << endl;
698         return string();
699 }
700
701
702 bool CVS::lockingToggleEnabled()
703 {
704         return false;
705 }
706
707
708 void CVS::revert()
709 {
710         // Reverts to the version in CVS repository and
711         // gets the updated version from the repository.
712         CvsStatus status = getStatus();
713         switch (status) {
714         case UpToDate:
715                 if (vcstatus != NOLOCKING)
716                         unedit();
717                 break;
718         case NeedsMerge:
719         case NeedsCheckout:
720         case LocallyModified: {
721                 FileName f(owner_->absFileName());
722                 f.removeFile();
723                 update(File, FileName());
724                 owner_->markClean();
725                 break;
726         }
727         case LocallyAdded:
728                 frontend::Alert::error(_("Revision control error."),
729                         _("The current file is not in repository.\n"
730                           "You have to check in the first revision before you can revert.")) ;
731                 break;
732         default:
733                 frontend::Alert::error(_("Revision control error."),
734                         bformat(_("Bad status when checking in changes.\n"
735                                           "\n'%1$s'\n\n"),
736                                 toString(status)));
737                 break;
738         }
739 }
740
741
742 void CVS::undoLast()
743 {
744         // merge the current with the previous version
745         // in a reverse patch kind of way, so that the
746         // result is to revert the last changes.
747         lyxerr << "Sorry, not implemented." << endl;
748 }
749
750
751 bool CVS::undoLastEnabled()
752 {
753         return false;
754 }
755
756
757 void CVS::getLog(FileName const & tmpf)
758 {
759         doVCCommand("cvs log " + getTarget(File)
760                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
761                     FileName(owner_->filePath()));
762 }
763
764
765 bool CVS::toggleReadOnlyEnabled()
766 {
767         return false;
768 }
769
770
771 string CVS::revisionInfo(LyXVC::RevisionInfo const info)
772 {
773         if (info == LyXVC::File)
774                 return version_;
775         return string();
776 }
777
778
779 bool CVS::prepareFileRevision(string const &, string &)
780 {
781         return false;
782 }
783
784
785 bool CVS::prepareFileRevisionEnabled()
786 {
787         return false;
788 }
789
790
791 /////////////////////////////////////////////////////////////////////
792 //
793 // SVN
794 //
795 /////////////////////////////////////////////////////////////////////
796
797 SVN::SVN(FileName const & m, FileName const & f)
798 {
799         owner_ = 0;
800         master_ = m;
801         file_ = f;
802         locked_mode_ = 0;
803         scanMaster();
804 }
805
806
807 FileName const SVN::findFile(FileName const & file)
808 {
809         // First we look for the .svn/entries in the same dir
810         // where we have file.
811         FileName const entries(onlyPath(file.absFileName()) + "/.svn/entries");
812         string const tmpf = onlyFileName(file.absFileName());
813         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under svn in `" << entries
814                              << "' for `" << tmpf << '\'');
815         if (entries.isReadableFile()) {
816                 // Ok we are at least in a SVN dir. Parse the .svn/entries
817                 // and see if we can find this file. We do a fast and
818                 // dirty parse here.
819                 ifstream ifs(entries.toFilesystemEncoding().c_str());
820                 string line, oldline;
821                 while (getline(ifs, line)) {
822                         if (line == "dir" || line == "file")
823                                 LYXERR(Debug::LYXVC, "\tEntries: " << oldline);
824                         if (oldline == tmpf && line == "file")
825                                 return entries;
826                         oldline = line;
827                 }
828         }
829         return FileName();
830 }
831
832
833 void SVN::scanMaster()
834 {
835         // vcstatus code is somewhat superflous, until we want
836         // to implement read-only toggle for svn.
837         vcstatus = NOLOCKING;
838         if (checkLockMode()) {
839                 if (isLocked()) {
840                         vcstatus = LOCKED;
841                 } else {
842                         vcstatus = UNLOCKED;
843                 }
844         }
845 }
846
847
848 bool SVN::checkLockMode()
849 {
850         FileName tmpf = FileName::tempName("lyxvcout");
851         if (tmpf.empty()){
852                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
853                 return N_("Error: Could not generate logfile.");
854         }
855
856         LYXERR(Debug::LYXVC, "Detecting locking mode...");
857         if (doVCCommandCall("svn proplist " + quoteName(file_.onlyFileName())
858                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
859                     file_.onlyPath()))
860                 return false;
861
862         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
863         string line;
864         bool ret = false;
865
866         while (ifs) {
867                 getline(ifs, line);
868                 LYXERR(Debug::LYXVC, line);
869                 if (contains(line, "svn:needs-lock"))
870                         ret = true;
871         }
872         LYXERR(Debug::LYXVC, "Locking enabled: " << ret);
873         ifs.close();
874         locked_mode_ = ret;
875         return ret;
876
877 }
878
879
880 bool SVN::isLocked() const
881 {
882         file_.refresh();
883         return !file_.isReadOnly();
884 }
885
886
887 void SVN::registrer(string const & /*msg*/)
888 {
889         doVCCommand("svn add -q " + quoteName(onlyFileName(owner_->absFileName())),
890                     FileName(owner_->filePath()));
891 }
892
893
894 string SVN::checkIn(string const & msg)
895 {
896         FileName tmpf = FileName::tempName("lyxvcout");
897         if (tmpf.empty()){
898                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
899                 return N_("Error: Could not generate logfile.");
900         }
901
902         doVCCommand("svn commit -m \"" + msg + "\" "
903                     + quoteName(onlyFileName(owner_->absFileName()))
904                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
905                     FileName(owner_->filePath()));
906
907         string log;
908         string res = scanLogFile(tmpf, log);
909         if (!res.empty())
910                 frontend::Alert::error(_("Revision control error."),
911                                 _("Error when committing to repository.\n"
912                                 "You have to manually resolve the problem.\n"
913                                 "LyX will reopen the document after you press OK."));
914         else
915                 fileLock(false, tmpf, log);
916
917         tmpf.erase();
918         return log.empty() ? string() : "SVN: " + log;
919 }
920
921
922 bool SVN::checkInEnabled()
923 {
924         if (locked_mode_)
925                 return isLocked();
926         else
927                 return true;
928 }
929
930
931 // FIXME Correctly return code should be checked instead of this.
932 // This would need another solution than just plain startscript.
933 // Hint from Andre': QProcess::readAllStandardError()...
934 string SVN::scanLogFile(FileName const & f, string & status)
935 {
936         ifstream ifs(f.toFilesystemEncoding().c_str());
937         string line;
938
939         while (ifs) {
940                 getline(ifs, line);
941                 LYXERR(Debug::LYXVC, line << "\n");
942                 if (!line.empty()) 
943                         status += line + "; ";
944                 if (prefixIs(line, "C ") || prefixIs(line, "CU ")
945                                          || contains(line, "Commit failed")) {
946                         ifs.close();
947                         return line;
948                 }
949                 if (contains(line, "svn:needs-lock")) {
950                         ifs.close();
951                         return line;
952                 }
953         }
954         ifs.close();
955         return string();
956 }
957
958
959 void SVN::fileLock(bool lock, FileName const & tmpf, string &status)
960 {
961         if (!locked_mode_ || (isLocked() == lock))
962                 return;
963
964         string const arg = lock ? "lock " : "unlock ";
965         doVCCommand("svn "+ arg + quoteName(onlyFileName(owner_->absFileName()))
966                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
967                     FileName(owner_->filePath()));
968
969         // Lock error messages go unfortunately on stderr and are unreachible this way.
970         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
971         string line;
972         while (ifs) {
973                 getline(ifs, line);
974                 if (!line.empty()) status += line + "; ";
975         }
976         ifs.close();
977
978         if (!isLocked() && lock)
979                 frontend::Alert::error(_("Revision control error."),
980                         _("Error while acquiring write lock.\n"
981                         "Another user is most probably editing\n"
982                         "the current document now!\n"
983                         "Also check the access to the repository."));
984         if (isLocked() && !lock)
985                 frontend::Alert::error(_("Revision control error."),
986                         _("Error while releasing write lock.\n"
987                         "Check the access to the repository."));
988 }
989
990
991 string SVN::checkOut()
992 {
993         FileName tmpf = FileName::tempName("lyxvcout");
994         if (tmpf.empty()) {
995                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
996                 return N_("Error: Could not generate logfile.");
997         }
998
999         doVCCommand("svn update --non-interactive " + quoteName(onlyFileName(owner_->absFileName()))
1000                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1001                     FileName(owner_->filePath()));
1002
1003         string log;
1004         string const res = scanLogFile(tmpf, log);
1005         if (!res.empty())
1006                 frontend::Alert::error(_("Revision control error."),
1007                         bformat(_("Error when updating from repository.\n"
1008                                 "You have to manually resolve the conflicts NOW!\n'%1$s'.\n\n"
1009                                 "After pressing OK, LyX will try to reopen the resolved document."),
1010                         from_local8bit(res)));
1011
1012         fileLock(true, tmpf, log);
1013
1014         tmpf.erase();
1015         return log.empty() ? string() : "SVN: " + log;
1016 }
1017
1018
1019 bool SVN::checkOutEnabled()
1020 {
1021         if (locked_mode_)
1022                 return !isLocked();
1023         else
1024                 return true;
1025 }
1026
1027
1028 string SVN::repoUpdate()
1029 {
1030         FileName tmpf = FileName::tempName("lyxvcout");
1031         if (tmpf.empty()) {
1032                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1033                 return N_("Error: Could not generate logfile.");
1034         }
1035
1036         doVCCommand("svn diff " + quoteName(owner_->filePath())
1037                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1038                 FileName(owner_->filePath()));
1039         docstring res = tmpf.fileContents("UTF-8");
1040         if (!res.empty()) {
1041                 LYXERR(Debug::LYXVC, "Diff detected:\n" << res);
1042                 docstring const file = from_utf8(owner_->filePath());
1043                 docstring text = bformat(_("There were detected changes "
1044                                 "in the working directory:\n%1$s\n\n"
1045                                 "In case of file conflict version of the local directory files "
1046                                 "will be preferred."
1047                                 "\n\nContinue?"), file);
1048                 int ret = frontend::Alert::prompt(_("Changes detected"),
1049                                 text, 0, 1, _("&Yes"), _("&No"), _("View &Log ..."));
1050                 if (ret == 2 ) {
1051                         dispatch(FuncRequest(LFUN_DIALOG_SHOW, "file " + tmpf.absFileName()));
1052                         ret = frontend::Alert::prompt(_("Changes detected"),
1053                                 text, 0, 1, _("&Yes"), _("&No"));
1054                         hideDialogs("file", 0);
1055                 }
1056                 if (ret == 1 ) {
1057                         tmpf.erase();
1058                         return string();
1059                 }
1060         }
1061
1062         // Reverting looks too harsh, see bug #6255.
1063         // doVCCommand("svn revert -R " + quoteName(owner_->filePath())
1064         // + " > " + quoteName(tmpf.toFilesystemEncoding()),
1065         // FileName(owner_->filePath()));
1066         // res = "Revert log:\n" + tmpf.fileContents("UTF-8");
1067         doVCCommand("svn update --accept mine-full " + quoteName(owner_->filePath())
1068                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
1069                 FileName(owner_->filePath()));
1070         res += "Update log:\n" + tmpf.fileContents("UTF-8");
1071
1072         LYXERR(Debug::LYXVC, res);
1073         tmpf.erase();
1074         return to_utf8(res);
1075 }
1076
1077
1078 bool SVN::repoUpdateEnabled()
1079 {
1080         return true;
1081 }
1082
1083
1084 string SVN::lockingToggle()
1085 {
1086         FileName tmpf = FileName::tempName("lyxvcout");
1087         if (tmpf.empty()) {
1088                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1089                 return N_("Error: Could not generate logfile.");
1090         }
1091
1092         int ret = doVCCommand("svn proplist " + quoteName(onlyFileName(owner_->absFileName()))
1093                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1094                     FileName(owner_->filePath()));
1095         if (ret)
1096                 return string();
1097
1098         string log;
1099         string res = scanLogFile(tmpf, log);
1100         bool locking = contains(res, "svn:needs-lock");
1101         if (!locking)
1102                 ret = doVCCommand("svn propset svn:needs-lock ON "
1103                     + quoteName(onlyFileName(owner_->absFileName()))
1104                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1105                     FileName(owner_->filePath()));
1106         else
1107                 ret = doVCCommand("svn propdel svn:needs-lock "
1108                     + quoteName(onlyFileName(owner_->absFileName()))
1109                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1110                     FileName(owner_->filePath()));
1111         if (ret)
1112                 return string();
1113
1114         tmpf.erase();
1115         frontend::Alert::warning(_("VCN File Locking"),
1116                 (locking ? _("Locking property unset.") : _("Locking property set.")) + "\n"
1117                 + _("Do not forget to commit the locking property into the repository."),
1118                 true);
1119
1120         return string("SVN: ") +  N_("Locking property set.");
1121 }
1122
1123
1124 bool SVN::lockingToggleEnabled()
1125 {
1126         return true;
1127 }
1128
1129
1130 void SVN::revert()
1131 {
1132         // Reverts to the version in CVS repository and
1133         // gets the updated version from the repository.
1134         string const fil = quoteName(onlyFileName(owner_->absFileName()));
1135
1136         doVCCommand("svn revert -q " + fil,
1137                     FileName(owner_->filePath()));
1138         owner_->markClean();
1139 }
1140
1141
1142 void SVN::undoLast()
1143 {
1144         // merge the current with the previous version
1145         // in a reverse patch kind of way, so that the
1146         // result is to revert the last changes.
1147         lyxerr << "Sorry, not implemented." << endl;
1148 }
1149
1150
1151 bool SVN::undoLastEnabled()
1152 {
1153         return false;
1154 }
1155
1156
1157 string SVN::revisionInfo(LyXVC::RevisionInfo const info)
1158 {
1159         if (info == LyXVC::Tree) {
1160                         if (rev_tree_cache_.empty())
1161                                 if (!getTreeRevisionInfo())
1162                                         rev_tree_cache_ = "?";
1163                         if (rev_tree_cache_ == "?")
1164                                 return string();
1165
1166                         return rev_tree_cache_;
1167         }
1168
1169         // fill the rest of the attributes for a single file
1170         if (rev_file_cache_.empty())
1171                 if (!getFileRevisionInfo())
1172                         rev_file_cache_ = "?";
1173
1174         switch (info) {
1175                 case LyXVC::File:
1176                         if (rev_file_cache_ == "?")
1177                                 return string();
1178                         return rev_file_cache_;
1179                 case LyXVC::Author:
1180                         return rev_author_cache_;
1181                 case LyXVC::Date:
1182                         return rev_date_cache_;
1183                 case LyXVC::Time:
1184                         return rev_time_cache_;
1185                 default: ;
1186
1187         }
1188
1189         return string();
1190 }
1191
1192
1193 bool SVN::getFileRevisionInfo()
1194 {
1195         FileName tmpf = FileName::tempName("lyxvcout");
1196         if (tmpf.empty()) {
1197                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1198                 return N_("Error: Could not generate logfile.");
1199         }
1200
1201         doVCCommand("svn info --xml " + quoteName(onlyFileName(owner_->absFileName()))
1202                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1203                     FileName(owner_->filePath()));
1204
1205         if (tmpf.empty())
1206                 return false;
1207
1208         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1209         string line;
1210         // commit log part
1211         bool c = false;
1212         string rev;
1213
1214         while (ifs) {
1215                 getline(ifs, line);
1216                 LYXERR(Debug::LYXVC, line);
1217                 if (prefixIs(line, "<commit"))
1218                         c = true;
1219                 if (c && prefixIs(line, "   revision=\"") && suffixIs(line, "\">")) {
1220                         string l1 = subst(line, "revision=\"", "");
1221                         string l2 = trim(subst(l1, "\">", ""));
1222                         if (isStrInt(l2))
1223                                 rev_file_cache_ = rev = l2;
1224                 }
1225                 if (c && prefixIs(line, "<author>") && suffixIs(line, "</author>")) {
1226                         string l1 = subst(line, "<author>", "");
1227                         string l2 = subst(l1, "</author>", "");
1228                         rev_author_cache_ = l2;
1229                 }
1230                 if (c && prefixIs(line, "<date>") && suffixIs(line, "</date>")) {
1231                         string l1 = subst(line, "<date>", "");
1232                         string l2 = subst(l1, "</date>", "");
1233                         l2 = split(l2, l1, 'T');
1234                         rev_date_cache_ = l1;
1235                         l2 = split(l2, l1, '.');
1236                         rev_time_cache_ = l1;
1237                 }
1238         }
1239
1240         ifs.close();
1241         tmpf.erase();
1242         return !rev.empty();
1243 }
1244
1245
1246 bool SVN::getTreeRevisionInfo()
1247 {
1248         FileName tmpf = FileName::tempName("lyxvcout");
1249         if (tmpf.empty()) {
1250                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1251                 return N_("Error: Could not generate logfile.");
1252         }
1253
1254         doVCCommand("svnversion -n . > " + quoteName(tmpf.toFilesystemEncoding()),
1255                     FileName(owner_->filePath()));
1256
1257         if (tmpf.empty())
1258                 return false;
1259
1260         // only first line in case something bad happens.
1261         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1262         string line;
1263         getline(ifs, line);
1264         ifs.close();
1265         tmpf.erase();
1266
1267         rev_tree_cache_ = line;
1268         return !line.empty();
1269 }
1270
1271
1272 void SVN::getLog(FileName const & tmpf)
1273 {
1274         doVCCommand("svn log " + quoteName(onlyFileName(owner_->absFileName()))
1275                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1276                     FileName(owner_->filePath()));
1277 }
1278
1279
1280 bool SVN::prepareFileRevision(string const & revis, string & f)
1281 {
1282         if (!isStrInt(revis))
1283                 return false;
1284
1285         int rev = convert<int>(revis);
1286         if (rev <= 0)
1287                 if (!getFileRevisionInfo())
1288                         return false;
1289         if (rev == 0)
1290                 rev = convert<int>(rev_file_cache_);
1291         // go back for minus rev
1292         else if (rev < 0) {
1293                 rev = rev + convert<int>(rev_file_cache_);
1294                 if (rev < 1)
1295                         return false;
1296         }
1297
1298         string revname = convert<string>(rev);
1299         FileName tmpf = FileName::tempName("lyxvcrev_" + revname + "_");
1300         if (tmpf.empty()) {
1301                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1302                 return N_("Error: Could not generate logfile.");
1303         }
1304
1305         doVCCommand("svn cat -r " + revname + " "
1306                       + quoteName(onlyFileName(owner_->absFileName()))
1307                       + " > " + quoteName(tmpf.toFilesystemEncoding()),
1308                 FileName(owner_->filePath()));
1309         if (tmpf.isFileEmpty())
1310                 return false;
1311
1312         f = tmpf.absFileName();
1313         return true;
1314 }
1315
1316
1317 bool SVN::prepareFileRevisionEnabled()
1318 {
1319         return true;
1320 }
1321
1322
1323
1324 bool SVN::toggleReadOnlyEnabled()
1325 {
1326         return false;
1327 }
1328
1329
1330 } // namespace lyx