Don't close file and pipe that were not opened.
[midnight-commander.git] / src / diffviewer / ydiff.c
blobe44c23aacfae421f9d12fa4573f07387eaa30348
1 /*
2 Copyright (C) 2007, 2010, 2011
3 The Free Software Foundation, Inc.
5 Written by:
6 Daniel Borca <dborca@yahoo.com>, 2007
7 Slava Zanko <slavazanko@gmail.com>, 2010
8 Andrew Borodin <aborodin@vmail.ru>, 2010
9 Ilia Maslakov <il.smind@gmail.com>, 2010
11 This file is part of the Midnight Commander.
13 The Midnight Commander is free software: you can redistribute it
14 and/or modify it under the terms of the GNU General Public License as
15 published by the Free Software Foundation, either version 3 of the License,
16 or (at your option) any later version.
18 The Midnight Commander is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License for more details.
23 You should have received a copy of the GNU General Public License
24 along with this program. If not, see <http://www.gnu.org/licenses/>.
28 #include <config.h>
29 #include <ctype.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <stdlib.h>
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <sys/wait.h>
37 #include "lib/global.h"
38 #include "lib/tty/tty.h"
39 #include "lib/tty/color.h"
40 #include "lib/tty/key.h"
41 #include "lib/skin.h" /* EDITOR_NORMAL_COLOR */
42 #include "lib/vfs/vfs.h" /* mc_opendir, mc_readdir, mc_closedir, */
43 #include "lib/util.h"
44 #include "lib/widget.h"
45 #include "lib/strutil.h"
46 #include "lib/strescape.h" /* strutils_glob_escape() */
47 #ifdef HAVE_CHARSET
48 #include "lib/charsets.h"
49 #endif
50 #include "lib/event.h" /* mc_event_raise() */
52 #include "src/filemanager/cmd.h" /* do_edit_at_line(), view_other_cmd() */
53 #include "src/filemanager/panel.h"
54 #include "src/filemanager/layout.h" /* Needed for get_current_index and get_other_panel */
56 #include "src/keybind-defaults.h"
57 #include "src/history.h"
58 #ifdef HAVE_CHARSET
59 #include "src/selcodepage.h"
60 #endif
62 #include "ydiff.h"
63 #include "internal.h"
65 /*** global variables ****************************************************************************/
67 /*** file scope macro definitions ****************************************************************/
69 #define g_array_foreach(a, TP, cbf) \
70 do { \
71 size_t g_array_foreach_i;\
72 TP *g_array_foreach_var = NULL; \
73 for (g_array_foreach_i = 0; g_array_foreach_i < a->len; g_array_foreach_i++) \
74 { \
75 g_array_foreach_var = &g_array_index (a, TP, g_array_foreach_i); \
76 (*cbf) (g_array_foreach_var); \
77 } \
78 } while (0)
80 #define FILE_READ_BUF 4096
81 #define FILE_FLAG_TEMP (1 << 0)
83 #define OPTX 56
84 #define OPTY 17
86 #define ADD_CH '+'
87 #define DEL_CH '-'
88 #define CHG_CH '*'
89 #define EQU_CH ' '
91 #define HDIFF_ENABLE 1
92 #define HDIFF_MINCTX 5
93 #define HDIFF_DEPTH 10
95 #define FILE_DIRTY(fs) \
96 do \
97 { \
98 (fs)->pos = 0; \
99 (fs)->len = 0; \
101 while (0)
103 /*** file scope type declarations ****************************************************************/
105 typedef enum
107 FROM_LEFT_TO_RIGHT,
108 FROM_RIGHT_TO_LEFT
109 } action_direction_t;
111 /*** file scope variables ************************************************************************/
113 /*** file scope functions ************************************************************************/
114 /* --------------------------------------------------------------------------------------------- */
116 static inline int
117 TAB_SKIP (int ts, int pos)
119 if (ts > 0 && ts < 9)
120 return ts - pos % ts;
121 else
122 return 8 - pos % 8;
125 /* --------------------------------------------------------------------------------------------- */
127 static gboolean
128 rewrite_backup_content (const vfs_path_t * from_file_name_vpath, const char *to_file_name)
130 FILE *backup_fd;
131 char *contents;
132 gsize length;
133 const char *from_file_name;
135 from_file_name = vfs_path_get_by_index (from_file_name_vpath, -1)->path;
136 if (!g_file_get_contents (from_file_name, &contents, &length, NULL))
137 return FALSE;
139 backup_fd = fopen (to_file_name, "w");
140 if (backup_fd == NULL)
142 g_free (contents);
143 return FALSE;
146 length = fwrite ((const void *) contents, length, 1, backup_fd);
148 fflush (backup_fd);
149 fclose (backup_fd);
150 g_free (contents);
151 return TRUE;
154 /* buffered I/O ************************************************************* */
157 * Try to open a temporary file.
158 * @note the name is not altered if this function fails
160 * @param[out] name address of a pointer to store the temporary name
161 * @returns file descriptor on success, negative on error
164 static int
165 open_temp (void **name)
167 int fd;
168 vfs_path_t *diff_file_name = NULL;
170 fd = mc_mkstemps (&diff_file_name, "mcdiff", NULL);
171 if (fd == -1)
173 message (D_ERROR, MSG_ERROR,
174 _("Cannot create temporary diff file\n%s"), unix_error_string (errno));
175 return -1;
177 *name = vfs_path_to_str (diff_file_name);
178 vfs_path_free (diff_file_name);
179 return fd;
182 /* --------------------------------------------------------------------------------------------- */
185 * Alocate file structure and associate file descriptor to it.
187 * @param fd file descriptor
188 * @returns file structure
191 static FBUF *
192 f_dopen (int fd)
194 FBUF *fs;
196 if (fd < 0)
197 return NULL;
199 fs = g_try_malloc (sizeof (FBUF));
200 if (fs == NULL)
201 return NULL;
203 fs->buf = g_try_malloc (FILE_READ_BUF);
204 if (fs->buf == NULL)
206 g_free (fs);
207 return NULL;
210 fs->fd = fd;
211 FILE_DIRTY (fs);
212 fs->flags = 0;
213 fs->data = NULL;
215 return fs;
218 /* --------------------------------------------------------------------------------------------- */
221 * Free file structure without closing the file.
223 * @param fs file structure
224 * @returns 0 on success, non-zero on error
227 static int
228 f_free (FBUF * fs)
230 int rv = 0;
232 if (fs->flags & FILE_FLAG_TEMP)
234 rv = unlink (fs->data);
235 g_free (fs->data);
237 g_free (fs->buf);
238 g_free (fs);
239 return rv;
242 /* --------------------------------------------------------------------------------------------- */
245 * Open a binary temporary file in R/W mode.
246 * @note the file will be deleted when closed
248 * @returns file structure
251 static FBUF *
252 f_temp (void)
254 int fd;
255 FBUF *fs;
257 fs = f_dopen (0);
258 if (fs == NULL)
259 return NULL;
261 fd = open_temp (&fs->data);
262 if (fd < 0)
264 f_free (fs);
265 return NULL;
268 fs->fd = fd;
269 fs->flags = FILE_FLAG_TEMP;
270 return fs;
273 /* --------------------------------------------------------------------------------------------- */
276 * Open a binary file in specified mode.
278 * @param filename file name
279 * @param flags open mode, a combination of O_RDONLY, O_WRONLY, O_RDWR
281 * @returns file structure
284 static FBUF *
285 f_open (const char *filename, int flags)
287 int fd;
288 FBUF *fs;
290 fs = f_dopen (0);
291 if (fs == NULL)
292 return NULL;
294 fd = open (filename, flags);
295 if (fd < 0)
297 f_free (fs);
298 return NULL;
301 fs->fd = fd;
302 return fs;
305 /* --------------------------------------------------------------------------------------------- */
308 * Read a line of bytes from file until newline or EOF.
309 * @note does not stop on null-byte
310 * @note buf will not be null-terminated
312 * @param buf destination buffer
313 * @param size size of buffer
314 * @param fs file structure
316 * @returns number of bytes read
320 static size_t
321 f_gets (char *buf, size_t size, FBUF * fs)
323 size_t j = 0;
327 int i;
328 int stop = 0;
330 for (i = fs->pos; j < size && i < fs->len && !stop; i++, j++)
332 buf[j] = fs->buf[i];
333 if (buf[j] == '\n')
334 stop = 1;
336 fs->pos = i;
338 if (j == size || stop)
339 break;
341 fs->pos = 0;
342 fs->len = read (fs->fd, fs->buf, FILE_READ_BUF);
344 while (fs->len > 0);
346 return j;
349 /* --------------------------------------------------------------------------------------------- */
352 * Seek into file.
353 * @note avoids thrashing read cache when possible
355 * @param fs file structure
356 * @param off offset
357 * @param whence seek directive: SEEK_SET, SEEK_CUR or SEEK_END
359 * @returns position in file, starting from begginning
363 static off_t
364 f_seek (FBUF * fs, off_t off, int whence)
366 off_t rv;
368 if (fs->len && whence != SEEK_END)
370 rv = lseek (fs->fd, 0, SEEK_CUR);
371 if (rv != -1)
373 if (whence == SEEK_CUR)
375 whence = SEEK_SET;
376 off += rv - fs->len + fs->pos;
378 if (off - rv >= -fs->len && off - rv <= 0)
380 fs->pos = fs->len + off - rv;
381 return off;
386 rv = lseek (fs->fd, off, whence);
387 if (rv != -1)
388 FILE_DIRTY (fs);
389 return rv;
392 /* --------------------------------------------------------------------------------------------- */
395 * Seek to the beginning of file, thrashing read cache.
397 * @param fs file structure
399 * @returns 0 if success, non-zero on error
402 static off_t
403 f_reset (FBUF * fs)
405 off_t rv;
407 rv = lseek (fs->fd, 0, SEEK_SET);
408 if (rv != -1)
409 FILE_DIRTY (fs);
410 return rv;
413 /* --------------------------------------------------------------------------------------------- */
416 * Write bytes to file.
417 * @note thrashes read cache
419 * @param fs file structure
420 * @param buf source buffer
421 * @param size size of buffer
423 * @returns number of written bytes, -1 on error
427 static ssize_t
428 f_write (FBUF * fs, const char *buf, size_t size)
430 ssize_t rv;
432 rv = write (fs->fd, buf, size);
433 if (rv >= 0)
434 FILE_DIRTY (fs);
435 return rv;
438 /* --------------------------------------------------------------------------------------------- */
441 * Truncate file to the current position.
442 * @note thrashes read cache
444 * @param fs file structure
446 * @returns current file size on success, negative on error
450 static off_t
451 f_trunc (FBUF * fs)
453 off_t off;
455 off = lseek (fs->fd, 0, SEEK_CUR);
456 if (off != -1)
458 int rv;
460 rv = ftruncate (fs->fd, off);
461 if (rv != 0)
462 off = -1;
463 else
464 FILE_DIRTY (fs);
466 return off;
469 /* --------------------------------------------------------------------------------------------- */
472 * Close file.
473 * @note if this is temporary file, it is deleted
475 * @param fs file structure
476 * @returns 0 on success, non-zero on error
480 static int
481 f_close (FBUF * fs)
483 int rv = -1;
485 if (fs != NULL)
487 rv = close (fs->fd);
488 f_free (fs);
491 return rv;
494 /* --------------------------------------------------------------------------------------------- */
497 * Create pipe stream to process.
499 * @param cmd shell command line
500 * @param flags open mode, either O_RDONLY or O_WRONLY
502 * @returns file structure
505 static FBUF *
506 p_open (const char *cmd, int flags)
508 FILE *f;
509 FBUF *fs;
510 const char *type = NULL;
512 if (flags == O_RDONLY)
513 type = "r";
514 else if (flags == O_WRONLY)
515 type = "w";
517 if (type == NULL)
518 return NULL;
520 fs = f_dopen (0);
521 if (fs == NULL)
522 return NULL;
524 f = popen (cmd, type);
525 if (f == NULL)
527 f_free (fs);
528 return NULL;
531 fs->fd = fileno (f);
532 fs->data = f;
533 return fs;
536 /* --------------------------------------------------------------------------------------------- */
539 * Close pipe stream.
541 * @param fs structure
542 * @returns 0 on success, non-zero on error
545 static int
546 p_close (FBUF * fs)
548 int rv = -1;
550 if (fs != NULL)
552 rv = pclose (fs->data);
553 f_free (fs);
556 return rv;
559 /* --------------------------------------------------------------------------------------------- */
562 * Get one char (byte) from string
564 * @param char * str, gboolean * result
565 * @returns int as character or 0 and result == FALSE if fail
568 static int
569 dview_get_byte (char *str, gboolean * result)
571 if (str == NULL)
573 *result = FALSE;
574 return 0;
576 *result = TRUE;
577 return (unsigned char) *str;
580 /* --------------------------------------------------------------------------------------------- */
583 * Get utf multibyte char from string
585 * @param char * str, int * char_width, gboolean * result
586 * @returns int as utf character or 0 and result == FALSE if fail
590 static int
591 dview_get_utf (char *str, int *char_width, gboolean * result)
593 int res = -1;
594 gunichar ch;
595 gchar *next_ch = NULL;
596 int width = 0;
598 *result = TRUE;
600 if (str == NULL)
602 *result = FALSE;
603 return 0;
606 res = g_utf8_get_char_validated (str, -1);
608 if (res < 0)
609 ch = *str;
610 else
612 ch = res;
613 /* Calculate UTF-8 char width */
614 next_ch = g_utf8_next_char (str);
615 if (next_ch != NULL)
616 width = next_ch - str;
617 else
618 ch = 0;
620 *char_width = width;
621 return ch;
624 /* --------------------------------------------------------------------------------------------- */
626 static int
627 dview_str_utf8_offset_to_pos (const char *text, size_t length)
629 ptrdiff_t result;
631 if (text == NULL || text[0] == '\0')
632 return length;
634 if (g_utf8_validate (text, -1, NULL))
635 result = g_utf8_offset_to_pointer (text, length) - text;
636 else
638 gunichar uni;
639 char *tmpbuf, *buffer;
641 buffer = tmpbuf = g_strdup (text);
642 while (tmpbuf[0] != '\0')
644 uni = g_utf8_get_char_validated (tmpbuf, -1);
645 if ((uni != (gunichar) (-1)) && (uni != (gunichar) (-2)))
646 tmpbuf = g_utf8_next_char (tmpbuf);
647 else
649 tmpbuf[0] = '.';
650 tmpbuf++;
653 result = g_utf8_offset_to_pointer (tmpbuf, length) - tmpbuf;
654 g_free (buffer);
656 return max (length, (size_t) result);
659 /* --------------------------------------------------------------------------------------------- */
661 /* diff parse *************************************************************** */
664 * Read decimal number from string.
666 * @param[in,out] str string to parse
667 * @param[out] n extracted number
668 * @returns 0 if success, otherwise non-zero
671 static int
672 scan_deci (const char **str, int *n)
674 const char *p = *str;
675 char *q;
677 errno = 0;
678 *n = strtol (p, &q, 10);
679 if (errno != 0 || p == q)
680 return -1;
681 *str = q;
682 return 0;
685 /* --------------------------------------------------------------------------------------------- */
688 * Parse line for diff statement.
690 * @param p string to parse
691 * @param ops list of diff statements
692 * @returns 0 if success, otherwise non-zero
695 static int
696 scan_line (const char *p, GArray * ops)
698 DIFFCMD op;
700 int f1, f2;
701 int t1, t2;
702 int cmd;
703 int range;
705 /* handle the following cases:
706 * NUMaNUM[,NUM]
707 * NUM[,NUM]cNUM[,NUM]
708 * NUM[,NUM]dNUM
709 * where NUM is a positive integer
712 if (scan_deci (&p, &f1) != 0 || f1 < 0)
713 return -1;
715 f2 = f1;
716 range = 0;
717 if (*p == ',')
719 p++;
720 if (scan_deci (&p, &f2) != 0 || f2 < f1)
721 return -1;
723 range = 1;
726 cmd = *p++;
727 if (cmd == 'a')
729 if (range != 0)
730 return -1;
732 else if (cmd != 'c' && cmd != 'd')
733 return -1;
735 if (scan_deci (&p, &t1) != 0 || t1 < 0)
736 return -1;
738 t2 = t1;
739 range = 0;
740 if (*p == ',')
742 p++;
743 if (scan_deci (&p, &t2) != 0 || t2 < t1)
744 return -1;
746 range = 1;
749 if (cmd == 'd' && range != 0)
750 return -1;
752 op.a[0][0] = f1;
753 op.a[0][1] = f2;
754 op.cmd = cmd;
755 op.a[1][0] = t1;
756 op.a[1][1] = t2;
757 g_array_append_val (ops, op);
758 return 0;
761 /* --------------------------------------------------------------------------------------------- */
764 * Parse diff output and extract diff statements.
766 * @param f stream to read from
767 * @param ops list of diff statements to fill
768 * @returns positive number indicating number of hunks, otherwise negative
771 static int
772 scan_diff (FBUF * f, GArray * ops)
774 int sz;
775 char buf[BUFSIZ];
777 while ((sz = f_gets (buf, sizeof (buf) - 1, f)) != 0)
779 if (isdigit (buf[0]))
781 if (buf[sz - 1] != '\n')
782 return -1;
784 buf[sz] = '\0';
785 if (scan_line (buf, ops) != 0)
786 return -1;
788 continue;
791 while (buf[sz - 1] != '\n' && (sz = f_gets (buf, sizeof (buf), f)) != 0)
795 return ops->len;
798 /* --------------------------------------------------------------------------------------------- */
801 * Invoke diff and extract diff statements.
803 * @param args extra arguments to be passed to diff
804 * @param extra more arguments to be passed to diff
805 * @param file1 first file to compare
806 * @param file2 second file to compare
807 * @param ops list of diff statements to fill
809 * @returns positive number indicating number of hunks, otherwise negative
812 static int
813 dff_execute (const char *args, const char *extra, const char *file1, const char *file2,
814 GArray * ops)
816 static const char *opt =
817 " --old-group-format='%df%(f=l?:,%dl)d%dE\n'"
818 " --new-group-format='%dea%dF%(F=L?:,%dL)\n'"
819 " --changed-group-format='%df%(f=l?:,%dl)c%dF%(F=L?:,%dL)\n'"
820 " --unchanged-group-format=''";
822 int rv;
823 FBUF *f;
824 char *cmd;
825 int code;
826 char *file1_esc, *file2_esc;
828 /* escape potential $ to avoid shell variable substitutions in popen() */
829 file1_esc = strutils_shell_escape (file1);
830 file2_esc = strutils_shell_escape (file2);
831 cmd = g_strdup_printf ("diff %s %s %s %s %s", args, extra, opt, file1_esc, file2_esc);
832 g_free (file1_esc);
833 g_free (file2_esc);
835 if (cmd == NULL)
836 return -1;
838 f = p_open (cmd, O_RDONLY);
839 g_free (cmd);
841 if (f == NULL)
842 return -1;
844 rv = scan_diff (f, ops);
845 code = p_close (f);
847 if (rv < 0 || code == -1 || !WIFEXITED (code) || WEXITSTATUS (code) == 2)
848 rv = -1;
850 return rv;
853 /* --------------------------------------------------------------------------------------------- */
856 * Reparse and display file according to diff statements.
858 * @param ord DIFF_LEFT if 1nd file is displayed , DIFF_RIGHT if 2nd file is displayed.
859 * @param filename file name to display
860 * @param ops list of diff statements
861 * @param printer printf-like function to be used for displaying
862 * @param ctx printer context
864 * @returns 0 if success, otherwise non-zero
867 static int
868 dff_reparse (diff_place_t ord, const char *filename, const GArray * ops, DFUNC printer, void *ctx)
870 size_t i;
871 FBUF *f;
872 size_t sz;
873 char buf[BUFSIZ];
874 int line = 0;
875 off_t off = 0;
876 const DIFFCMD *op;
877 diff_place_t eff;
878 int add_cmd;
879 int del_cmd;
881 f = f_open (filename, O_RDONLY);
882 if (f == NULL)
883 return -1;
885 ord &= 1;
886 eff = ord;
888 add_cmd = 'a';
889 del_cmd = 'd';
890 if (ord != 0)
892 add_cmd = 'd';
893 del_cmd = 'a';
895 #define F1 a[eff][0]
896 #define F2 a[eff][1]
897 #define T1 a[ ord^1 ][0]
898 #define T2 a[ ord^1 ][1]
899 for (i = 0; i < ops->len; i++)
901 int n;
903 op = &g_array_index (ops, DIFFCMD, i);
904 n = op->F1 - (op->cmd != add_cmd);
906 while (line < n && (sz = f_gets (buf, sizeof (buf), f)) != 0)
908 line++;
909 printer (ctx, EQU_CH, line, off, sz, buf);
910 off += sz;
911 while (buf[sz - 1] != '\n')
913 sz = f_gets (buf, sizeof (buf), f);
914 if (sz == 0)
916 printer (ctx, 0, 0, 0, 1, "\n");
917 break;
919 printer (ctx, 0, 0, 0, sz, buf);
920 off += sz;
924 if (line != n)
925 goto err;
927 if (op->cmd == add_cmd)
929 n = op->T2 - op->T1 + 1;
930 while (n != 0)
932 printer (ctx, DEL_CH, 0, 0, 1, "\n");
933 n--;
937 if (op->cmd == del_cmd)
939 n = op->F2 - op->F1 + 1;
940 while (n != 0 && (sz = f_gets (buf, sizeof (buf), f)) != 0)
942 line++;
943 printer (ctx, ADD_CH, line, off, sz, buf);
944 off += sz;
945 while (buf[sz - 1] != '\n')
947 sz = f_gets (buf, sizeof (buf), f);
948 if (sz == 0)
950 printer (ctx, 0, 0, 0, 1, "\n");
951 break;
953 printer (ctx, 0, 0, 0, sz, buf);
954 off += sz;
956 n--;
959 if (n != 0)
960 goto err;
963 if (op->cmd == 'c')
965 n = op->F2 - op->F1 + 1;
966 while (n != 0 && (sz = f_gets (buf, sizeof (buf), f)) != 0)
968 line++;
969 printer (ctx, CHG_CH, line, off, sz, buf);
970 off += sz;
971 while (buf[sz - 1] != '\n')
973 sz = f_gets (buf, sizeof (buf), f);
974 if (sz == 0)
976 printer (ctx, 0, 0, 0, 1, "\n");
977 break;
979 printer (ctx, 0, 0, 0, sz, buf);
980 off += sz;
982 n--;
985 if (n != 0)
986 goto err;
988 n = op->T2 - op->T1 - (op->F2 - op->F1);
989 while (n > 0)
991 printer (ctx, CHG_CH, 0, 0, 1, "\n");
992 n--;
996 #undef T2
997 #undef T1
998 #undef F2
999 #undef F1
1001 while ((sz = f_gets (buf, sizeof (buf), f)) != 0)
1003 line++;
1004 printer (ctx, EQU_CH, line, off, sz, buf);
1005 off += sz;
1006 while (buf[sz - 1] != '\n')
1008 sz = f_gets (buf, sizeof (buf), f);
1009 if (sz == 0)
1011 printer (ctx, 0, 0, 0, 1, "\n");
1012 break;
1014 printer (ctx, 0, 0, 0, sz, buf);
1015 off += sz;
1019 f_close (f);
1020 return 0;
1022 err:
1023 f_close (f);
1024 return -1;
1027 /* --------------------------------------------------------------------------------------------- */
1029 /* horizontal diff ********************************************************** */
1032 * Longest common substring.
1034 * @param s first string
1035 * @param m length of first string
1036 * @param t second string
1037 * @param n length of second string
1038 * @param ret list of offsets for longest common substrings inside each string
1039 * @param min minimum length of common substrings
1041 * @returns 0 if success, nonzero otherwise
1044 static int
1045 lcsubstr (const char *s, int m, const char *t, int n, GArray * ret, int min)
1047 int i, j;
1048 int *Lprev, *Lcurr;
1049 int z = 0;
1051 if (m < min || n < min)
1053 /* XXX early culling */
1054 return 0;
1057 Lprev = g_try_new0 (int, n + 1);
1058 if (Lprev == NULL)
1059 return -1;
1061 Lcurr = g_try_new0 (int, n + 1);
1062 if (Lcurr == NULL)
1064 g_free (Lprev);
1065 return -1;
1068 for (i = 0; i < m; i++)
1070 int *L;
1072 L = Lprev;
1073 Lprev = Lcurr;
1074 Lcurr = L;
1075 #ifdef USE_MEMSET_IN_LCS
1076 memset (Lcurr, 0, (n + 1) * sizeof (int));
1077 #endif
1078 for (j = 0; j < n; j++)
1080 #ifndef USE_MEMSET_IN_LCS
1081 Lcurr[j + 1] = 0;
1082 #endif
1083 if (s[i] == t[j])
1085 int v;
1087 v = Lprev[j] + 1;
1088 Lcurr[j + 1] = v;
1089 if (z < v)
1091 z = v;
1092 g_array_set_size (ret, 0);
1094 if (z == v && z >= min)
1096 int off0, off1;
1097 size_t k;
1099 off0 = i - z + 1;
1100 off1 = j - z + 1;
1102 for (k = 0; k < ret->len; k++)
1104 PAIR *p = (PAIR *) g_array_index (ret, PAIR, k);
1105 if ((*p)[0] == off0 || (*p)[1] >= off1)
1106 break;
1108 if (k == ret->len)
1110 PAIR p2;
1112 p2[0] = off0;
1113 p2[1] = off1;
1114 g_array_append_val (ret, p2);
1121 free (Lcurr);
1122 free (Lprev);
1123 return z;
1126 /* --------------------------------------------------------------------------------------------- */
1129 * Scan recursively for common substrings and build ranges.
1131 * @param s first string
1132 * @param t second string
1133 * @param bracket current limits for both of the strings
1134 * @param min minimum length of common substrings
1135 * @param hdiff list of horizontal diff ranges to fill
1136 * @param depth recursion depth
1138 * @returns 0 if success, nonzero otherwise
1141 static gboolean
1142 hdiff_multi (const char *s, const char *t, const BRACKET bracket, int min, GArray * hdiff,
1143 unsigned int depth)
1145 BRACKET p;
1147 if (depth-- != 0)
1149 GArray *ret;
1150 BRACKET b;
1151 int len;
1153 ret = g_array_new (FALSE, TRUE, sizeof (PAIR));
1154 if (ret == NULL)
1155 return FALSE;
1157 len = lcsubstr (s + bracket[DIFF_LEFT].off, bracket[DIFF_LEFT].len,
1158 t + bracket[DIFF_RIGHT].off, bracket[DIFF_RIGHT].len, ret, min);
1159 if (ret->len != 0)
1161 size_t k = 0;
1162 const PAIR *data = (const PAIR *) &g_array_index (ret, PAIR, 0);
1163 const PAIR *data2;
1165 b[DIFF_LEFT].off = bracket[DIFF_LEFT].off;
1166 b[DIFF_LEFT].len = (*data)[0];
1167 b[DIFF_RIGHT].off = bracket[DIFF_RIGHT].off;
1168 b[DIFF_RIGHT].len = (*data)[1];
1169 if (!hdiff_multi (s, t, b, min, hdiff, depth))
1170 return FALSE;
1172 for (k = 0; k < ret->len - 1; k++)
1174 data = (const PAIR *) &g_array_index (ret, PAIR, k);
1175 data2 = (const PAIR *) &g_array_index (ret, PAIR, k + 1);
1176 b[DIFF_LEFT].off = bracket[DIFF_LEFT].off + (*data)[0] + len;
1177 b[DIFF_LEFT].len = (*data2)[0] - (*data)[0] - len;
1178 b[DIFF_RIGHT].off = bracket[DIFF_RIGHT].off + (*data)[1] + len;
1179 b[DIFF_RIGHT].len = (*data2)[1] - (*data)[1] - len;
1180 if (!hdiff_multi (s, t, b, min, hdiff, depth))
1181 return FALSE;
1183 data = (const PAIR *) &g_array_index (ret, PAIR, k);
1184 b[DIFF_LEFT].off = bracket[DIFF_LEFT].off + (*data)[0] + len;
1185 b[DIFF_LEFT].len = bracket[DIFF_LEFT].len - (*data)[0] - len;
1186 b[DIFF_RIGHT].off = bracket[DIFF_RIGHT].off + (*data)[1] + len;
1187 b[DIFF_RIGHT].len = bracket[DIFF_RIGHT].len - (*data)[1] - len;
1188 if (!hdiff_multi (s, t, b, min, hdiff, depth))
1189 return FALSE;
1191 g_array_free (ret, TRUE);
1192 return TRUE;
1196 p[DIFF_LEFT].off = bracket[DIFF_LEFT].off;
1197 p[DIFF_LEFT].len = bracket[DIFF_LEFT].len;
1198 p[DIFF_RIGHT].off = bracket[DIFF_RIGHT].off;
1199 p[DIFF_RIGHT].len = bracket[DIFF_RIGHT].len;
1200 g_array_append_val (hdiff, p);
1202 return TRUE;
1205 /* --------------------------------------------------------------------------------------------- */
1208 * Build list of horizontal diff ranges.
1210 * @param s first string
1211 * @param m length of first string
1212 * @param t second string
1213 * @param n length of second string
1214 * @param min minimum length of common substrings
1215 * @param hdiff list of horizontal diff ranges to fill
1216 * @param depth recursion depth
1218 * @returns 0 if success, nonzero otherwise
1221 static gboolean
1222 hdiff_scan (const char *s, int m, const char *t, int n, int min, GArray * hdiff, unsigned int depth)
1224 int i;
1225 BRACKET b;
1227 /* dumbscan (single horizontal diff) -- does not compress whitespace */
1228 for (i = 0; i < m && i < n && s[i] == t[i]; i++)
1230 for (; m > i && n > i && s[m - 1] == t[n - 1]; m--, n--)
1233 b[DIFF_LEFT].off = i;
1234 b[DIFF_LEFT].len = m - i;
1235 b[DIFF_RIGHT].off = i;
1236 b[DIFF_RIGHT].len = n - i;
1238 /* smartscan (multiple horizontal diff) */
1239 return hdiff_multi (s, t, b, min, hdiff, depth);
1242 /* --------------------------------------------------------------------------------------------- */
1244 /* read line **************************************************************** */
1247 * Check if character is inside horizontal diff limits.
1249 * @param k rank of character inside line
1250 * @param hdiff horizontal diff structure
1251 * @param ord DIFF_LEFT if reading from first file, DIFF_RIGHT if reading from 2nd file
1253 * @returns TRUE if inside hdiff limits, FALSE otherwise
1256 static gboolean
1257 is_inside (int k, GArray * hdiff, diff_place_t ord)
1259 size_t i;
1260 BRACKET *b;
1262 for (i = 0; i < hdiff->len; i++)
1264 int start, end;
1266 b = &g_array_index (hdiff, BRACKET, i);
1267 start = (*b)[ord].off;
1268 end = start + (*b)[ord].len;
1269 if (k >= start && k < end)
1270 return TRUE;
1272 return FALSE;
1275 /* --------------------------------------------------------------------------------------------- */
1278 * Copy 'src' to 'dst' expanding tabs.
1279 * @note The procedure returns when all bytes are consumed from 'src'
1281 * @param dst destination buffer
1282 * @param src source buffer
1283 * @param srcsize size of src buffer
1284 * @param base virtual base of this string, needed to calculate tabs
1285 * @param ts tab size
1287 * @returns new virtual base
1290 static int
1291 cvt_cpy (char *dst, const char *src, size_t srcsize, int base, int ts)
1293 int i;
1295 for (i = 0; srcsize != 0; i++, src++, dst++, srcsize--)
1297 *dst = *src;
1298 if (*src == '\t')
1300 int j;
1302 j = TAB_SKIP (ts, i + base);
1303 i += j - 1;
1304 while (j-- > 0)
1305 *dst++ = ' ';
1306 dst--;
1309 return i + base;
1312 /* --------------------------------------------------------------------------------------------- */
1315 * Copy 'src' to 'dst' expanding tabs.
1317 * @param dst destination buffer
1318 * @param dstsize size of dst buffer
1319 * @param[in,out] _src source buffer
1320 * @param srcsize size of src buffer
1321 * @param base virtual base of this string, needed to calculate tabs
1322 * @param ts tab size
1324 * @returns new virtual base
1326 * @note The procedure returns when all bytes are consumed from 'src'
1327 * or 'dstsize' bytes are written to 'dst'
1328 * @note Upon return, 'src' points to the first unwritten character in source
1331 static int
1332 cvt_ncpy (char *dst, int dstsize, const char **_src, size_t srcsize, int base, int ts)
1334 int i;
1335 const char *src = *_src;
1337 for (i = 0; i < dstsize && srcsize != 0; i++, src++, dst++, srcsize--)
1339 *dst = *src;
1340 if (*src == '\t')
1342 int j;
1344 j = TAB_SKIP (ts, i + base);
1345 if (j > dstsize - i)
1346 j = dstsize - i;
1347 i += j - 1;
1348 while (j-- > 0)
1349 *dst++ = ' ';
1350 dst--;
1353 *_src = src;
1354 return i + base;
1357 /* --------------------------------------------------------------------------------------------- */
1360 * Read line from memory, converting tabs to spaces and padding with spaces.
1362 * @param src buffer to read from
1363 * @param srcsize size of src buffer
1364 * @param dst buffer to read to
1365 * @param dstsize size of dst buffer, excluding trailing null
1366 * @param skip number of characters to skip
1367 * @param ts tab size
1368 * @param show_cr show trailing carriage return as ^M
1370 * @returns negative on error, otherwise number of bytes except padding
1373 static int
1374 cvt_mget (const char *src, size_t srcsize, char *dst, int dstsize, int skip, int ts, int show_cr)
1376 int sz = 0;
1378 if (src != NULL)
1380 int i;
1381 char *tmp = dst;
1382 const int base = 0;
1384 for (i = 0; dstsize != 0 && srcsize != 0 && *src != '\n'; i++, src++, srcsize--)
1386 if (*src == '\t')
1388 int j;
1390 j = TAB_SKIP (ts, i + base);
1391 i += j - 1;
1392 while (j-- > 0)
1394 if (skip > 0)
1395 skip--;
1396 else if (dstsize != 0)
1398 dstsize--;
1399 *dst++ = ' ';
1403 else if (src[0] == '\r' && (srcsize == 1 || src[1] == '\n'))
1405 if (skip == 0 && show_cr)
1407 if (dstsize > 1)
1409 dstsize -= 2;
1410 *dst++ = '^';
1411 *dst++ = 'M';
1413 else
1415 dstsize--;
1416 *dst++ = '.';
1419 break;
1421 else if (skip > 0)
1423 int utf_ch = 0;
1424 gboolean res;
1425 int w;
1427 skip--;
1428 utf_ch = dview_get_utf ((char *) src, &w, &res);
1429 if (w > 1)
1430 skip += w - 1;
1431 if (!g_unichar_isprint (utf_ch))
1432 utf_ch = '.';
1434 else
1436 dstsize--;
1437 *dst++ = *src;
1440 sz = dst - tmp;
1442 while (dstsize != 0)
1444 dstsize--;
1445 *dst++ = ' ';
1447 *dst = '\0';
1448 return sz;
1451 /* --------------------------------------------------------------------------------------------- */
1454 * Read line from memory and build attribute array.
1456 * @param src buffer to read from
1457 * @param srcsize size of src buffer
1458 * @param dst buffer to read to
1459 * @param dstsize size of dst buffer, excluding trailing null
1460 * @param skip number of characters to skip
1461 * @param ts tab size
1462 * @param show_cr show trailing carriage return as ^M
1463 * @param hdiff horizontal diff structure
1464 * @param ord DIFF_LEFT if reading from first file, DIFF_RIGHT if reading from 2nd file
1465 * @param att buffer of attributes
1467 * @returns negative on error, otherwise number of bytes except padding
1470 static int
1471 cvt_mgeta (const char *src, size_t srcsize, char *dst, int dstsize, int skip, int ts, int show_cr,
1472 GArray * hdiff, diff_place_t ord, char *att)
1474 int sz = 0;
1476 if (src != NULL)
1478 int i, k;
1479 char *tmp = dst;
1480 const int base = 0;
1482 for (i = 0, k = 0; dstsize != 0 && srcsize != 0 && *src != '\n'; i++, k++, src++, srcsize--)
1484 if (*src == '\t')
1486 int j;
1488 j = TAB_SKIP (ts, i + base);
1489 i += j - 1;
1490 while (j-- > 0)
1492 if (skip != 0)
1493 skip--;
1494 else if (dstsize != 0)
1496 dstsize--;
1497 *att++ = is_inside (k, hdiff, ord);
1498 *dst++ = ' ';
1502 else if (src[0] == '\r' && (srcsize == 1 || src[1] == '\n'))
1504 if (skip == 0 && show_cr)
1506 if (dstsize > 1)
1508 dstsize -= 2;
1509 *att++ = is_inside (k, hdiff, ord);
1510 *dst++ = '^';
1511 *att++ = is_inside (k, hdiff, ord);
1512 *dst++ = 'M';
1514 else
1516 dstsize--;
1517 *att++ = is_inside (k, hdiff, ord);
1518 *dst++ = '.';
1521 break;
1523 else if (skip != 0)
1525 int utf_ch = 0;
1526 gboolean res;
1527 int w;
1529 skip--;
1530 utf_ch = dview_get_utf ((char *) src, &w, &res);
1531 if (w > 1)
1532 skip += w - 1;
1533 if (!g_unichar_isprint (utf_ch))
1534 utf_ch = '.';
1536 else
1538 dstsize--;
1539 *att++ = is_inside (k, hdiff, ord);
1540 *dst++ = *src;
1543 sz = dst - tmp;
1545 while (dstsize != 0)
1547 dstsize--;
1548 *att++ = '\0';
1549 *dst++ = ' ';
1551 *dst = '\0';
1552 return sz;
1555 /* --------------------------------------------------------------------------------------------- */
1558 * Read line from file, converting tabs to spaces and padding with spaces.
1560 * @param f file stream to read from
1561 * @param off offset of line inside file
1562 * @param dst buffer to read to
1563 * @param dstsize size of dst buffer, excluding trailing null
1564 * @param skip number of characters to skip
1565 * @param ts tab size
1566 * @param show_cr show trailing carriage return as ^M
1568 * @returns negative on error, otherwise number of bytes except padding
1571 static int
1572 cvt_fget (FBUF * f, off_t off, char *dst, size_t dstsize, int skip, int ts, int show_cr)
1574 int base = 0;
1575 int old_base = base;
1576 size_t amount = dstsize;
1577 size_t useful, offset;
1578 size_t i;
1579 size_t sz;
1580 int lastch = '\0';
1581 const char *q = NULL;
1582 char tmp[BUFSIZ]; /* XXX capacity must be >= max{dstsize + 1, amount} */
1583 char cvt[BUFSIZ]; /* XXX capacity must be >= MAX_TAB_WIDTH * amount */
1585 if (sizeof (tmp) < amount || sizeof (tmp) <= dstsize || sizeof (cvt) < 8 * amount)
1587 /* abnormal, but avoid buffer overflow */
1588 memset (dst, ' ', dstsize);
1589 dst[dstsize] = '\0';
1590 return 0;
1593 f_seek (f, off, SEEK_SET);
1595 while (skip > base)
1597 old_base = base;
1598 sz = f_gets (tmp, amount, f);
1599 if (sz == 0)
1600 break;
1602 base = cvt_cpy (cvt, tmp, sz, old_base, ts);
1603 if (cvt[base - old_base - 1] == '\n')
1605 q = &cvt[base - old_base - 1];
1606 base = old_base + q - cvt + 1;
1607 break;
1611 if (base < skip)
1613 memset (dst, ' ', dstsize);
1614 dst[dstsize] = '\0';
1615 return 0;
1618 useful = base - skip;
1619 offset = skip - old_base;
1621 if (useful <= dstsize)
1623 if (useful != 0)
1624 memmove (dst, cvt + offset, useful);
1626 if (q == NULL)
1628 sz = f_gets (tmp, dstsize - useful + 1, f);
1629 if (sz != 0)
1631 const char *ptr = tmp;
1633 useful += cvt_ncpy (dst + useful, dstsize - useful, &ptr, sz, base, ts) - base;
1634 if (ptr < tmp + sz)
1635 lastch = *ptr;
1638 sz = useful;
1640 else
1642 memmove (dst, cvt + offset, dstsize);
1643 sz = dstsize;
1644 lastch = cvt[offset + dstsize];
1647 dst[sz] = lastch;
1648 for (i = 0; i < sz && dst[i] != '\n'; i++)
1650 if (dst[i] == '\r' && dst[i + 1] == '\n')
1652 if (show_cr)
1654 if (i + 1 < dstsize)
1656 dst[i++] = '^';
1657 dst[i++] = 'M';
1659 else
1661 dst[i++] = '*';
1664 break;
1668 for (; i < dstsize; i++)
1669 dst[i] = ' ';
1670 dst[i] = '\0';
1671 return sz;
1674 /* --------------------------------------------------------------------------------------------- */
1675 /* diff printers et al ****************************************************** */
1677 static void
1678 cc_free_elt (void *elt)
1680 DIFFLN *p = elt;
1682 if (p != NULL)
1683 g_free (p->p);
1686 /* --------------------------------------------------------------------------------------------- */
1688 static int
1689 printer (void *ctx, int ch, int line, off_t off, size_t sz, const char *str)
1691 GArray *a = ((PRINTER_CTX *) ctx)->a;
1692 DSRC dsrc = ((PRINTER_CTX *) ctx)->dsrc;
1694 if (ch != 0)
1696 DIFFLN p;
1698 p.p = NULL;
1699 p.ch = ch;
1700 p.line = line;
1701 p.u.off = off;
1702 if (dsrc == DATA_SRC_MEM && line != 0)
1704 if (sz != 0 && str[sz - 1] == '\n')
1705 sz--;
1706 if (sz > 0)
1707 p.p = g_strndup (str, sz);
1708 p.u.len = sz;
1710 g_array_append_val (a, p);
1712 else if (dsrc == DATA_SRC_MEM)
1714 DIFFLN *p;
1716 p = &g_array_index (a, DIFFLN, a->len - 1);
1717 if (sz != 0 && str[sz - 1] == '\n')
1718 sz--;
1719 if (sz != 0)
1721 size_t new_size;
1722 char *q;
1724 new_size = p->u.len + sz;
1725 q = g_realloc (p->p, new_size);
1726 memcpy (q + p->u.len, str, sz);
1727 p->p = q;
1729 p->u.len += sz;
1731 if (dsrc == DATA_SRC_TMP && (line != 0 || ch == 0))
1733 FBUF *f = ((PRINTER_CTX *) ctx)->f;
1734 f_write (f, str, sz);
1736 return 0;
1739 /* --------------------------------------------------------------------------------------------- */
1741 static int
1742 redo_diff (WDiff * dview)
1744 FBUF *const *f = dview->f;
1745 PRINTER_CTX ctx;
1746 GArray *ops;
1747 int ndiff;
1748 int rv;
1749 char extra[256];
1751 extra[0] = '\0';
1752 if (dview->opt.quality == 2)
1753 strcat (extra, " -d");
1754 if (dview->opt.quality == 1)
1755 strcat (extra, " --speed-large-files");
1756 if (dview->opt.strip_trailing_cr)
1757 strcat (extra, " --strip-trailing-cr");
1758 if (dview->opt.ignore_tab_expansion)
1759 strcat (extra, " -E");
1760 if (dview->opt.ignore_space_change)
1761 strcat (extra, " -b");
1762 if (dview->opt.ignore_all_space)
1763 strcat (extra, " -w");
1764 if (dview->opt.ignore_case)
1765 strcat (extra, " -i");
1767 if (dview->dsrc != DATA_SRC_MEM)
1769 f_reset (f[DIFF_LEFT]);
1770 f_reset (f[DIFF_RIGHT]);
1773 ops = g_array_new (FALSE, FALSE, sizeof (DIFFCMD));
1774 ndiff = dff_execute (dview->args, extra, dview->file[DIFF_LEFT], dview->file[DIFF_RIGHT], ops);
1775 if (ndiff < 0)
1777 if (ops != NULL)
1778 g_array_free (ops, TRUE);
1779 return -1;
1782 ctx.dsrc = dview->dsrc;
1784 rv = 0;
1785 ctx.a = dview->a[DIFF_LEFT];
1786 ctx.f = f[DIFF_LEFT];
1787 rv |= dff_reparse (DIFF_LEFT, dview->file[DIFF_LEFT], ops, printer, &ctx);
1789 ctx.a = dview->a[DIFF_RIGHT];
1790 ctx.f = f[DIFF_RIGHT];
1791 rv |= dff_reparse (DIFF_RIGHT, dview->file[DIFF_RIGHT], ops, printer, &ctx);
1793 if (ops != NULL)
1794 g_array_free (ops, TRUE);
1796 if (rv != 0 || dview->a[DIFF_LEFT]->len != dview->a[DIFF_RIGHT]->len)
1797 return -1;
1799 if (dview->dsrc == DATA_SRC_TMP)
1801 f_trunc (f[DIFF_LEFT]);
1802 f_trunc (f[DIFF_RIGHT]);
1805 if (dview->dsrc == DATA_SRC_MEM && HDIFF_ENABLE)
1807 dview->hdiff = g_ptr_array_new ();
1808 if (dview->hdiff != NULL)
1810 size_t i;
1811 const DIFFLN *p;
1812 const DIFFLN *q;
1814 for (i = 0; i < dview->a[DIFF_LEFT]->len; i++)
1816 GArray *h = NULL;
1818 p = &g_array_index (dview->a[DIFF_LEFT], DIFFLN, i);
1819 q = &g_array_index (dview->a[DIFF_RIGHT], DIFFLN, i);
1820 if (p->line && q->line && p->ch == CHG_CH)
1822 h = g_array_new (FALSE, FALSE, sizeof (BRACKET));
1823 if (h != NULL)
1825 gboolean runresult;
1827 runresult =
1828 hdiff_scan (p->p, p->u.len, q->p, q->u.len, HDIFF_MINCTX, h,
1829 HDIFF_DEPTH);
1830 if (!runresult)
1832 g_array_free (h, TRUE);
1833 h = NULL;
1837 g_ptr_array_add (dview->hdiff, h);
1841 return ndiff;
1844 /* --------------------------------------------------------------------------------------------- */
1846 static void
1847 destroy_hdiff (WDiff * dview)
1849 if (dview->hdiff != NULL)
1851 int i;
1852 int len;
1854 len = dview->a[DIFF_LEFT]->len;
1856 for (i = 0; i < len; i++)
1858 GArray *h;
1860 h = (GArray *) g_ptr_array_index (dview->hdiff, i);
1861 if (h != NULL)
1862 g_array_free (h, TRUE);
1864 g_ptr_array_free (dview->hdiff, TRUE);
1865 dview->hdiff = NULL;
1868 mc_search_free (dview->search.handle);
1869 dview->search.handle = NULL;
1870 g_free (dview->search.last_string);
1871 dview->search.last_string = NULL;
1874 /* --------------------------------------------------------------------------------------------- */
1875 /* stuff ******************************************************************** */
1877 static int
1878 get_digits (unsigned int n)
1880 int d = 1;
1882 while (n /= 10)
1883 d++;
1884 return d;
1887 /* --------------------------------------------------------------------------------------------- */
1889 static int
1890 get_line_numbers (const GArray * a, size_t pos, int *linenum, int *lineofs)
1892 const DIFFLN *p;
1894 *linenum = 0;
1895 *lineofs = 0;
1897 if (a->len != 0)
1899 if (pos >= a->len)
1900 pos = a->len - 1;
1902 p = &g_array_index (a, DIFFLN, pos);
1904 if (p->line == 0)
1906 int n;
1908 for (n = pos; n > 0; n--)
1910 p--;
1911 if (p->line != 0)
1912 break;
1914 *lineofs = pos - n + 1;
1917 *linenum = p->line;
1919 return 0;
1922 /* --------------------------------------------------------------------------------------------- */
1924 static int
1925 calc_nwidth (const GArray ** const a)
1927 int l1, o1;
1928 int l2, o2;
1930 get_line_numbers (a[DIFF_LEFT], a[DIFF_LEFT]->len - 1, &l1, &o1);
1931 get_line_numbers (a[DIFF_RIGHT], a[DIFF_RIGHT]->len - 1, &l2, &o2);
1932 if (l1 < l2)
1933 l1 = l2;
1934 return get_digits (l1);
1937 /* --------------------------------------------------------------------------------------------- */
1939 static int
1940 find_prev_hunk (const GArray * a, int pos)
1942 #if 1
1943 while (pos > 0 && ((DIFFLN *) & g_array_index (a, DIFFLN, pos))->ch != EQU_CH)
1944 pos--;
1945 while (pos > 0 && ((DIFFLN *) & g_array_index (a, DIFFLN, pos))->ch == EQU_CH)
1946 pos--;
1947 while (pos > 0 && ((DIFFLN *) & g_array_index (a, DIFFLN, pos))->ch != EQU_CH)
1948 pos--;
1949 if (pos > 0 && (size_t) pos < a->len)
1950 pos++;
1951 #else
1952 while (pos > 0 && ((DIFFLN *) & g_array_index (a, DIFFLN, pos - 1))->ch == EQU_CH)
1953 pos--;
1954 while (pos > 0 && ((DIFFLN *) & g_array_index (a, DIFFLN, pos - 1))->ch != EQU_CH)
1955 pos--;
1956 #endif
1958 return pos;
1961 /* --------------------------------------------------------------------------------------------- */
1963 static size_t
1964 find_next_hunk (const GArray * a, size_t pos)
1966 while (pos < a->len && ((DIFFLN *) & g_array_index (a, DIFFLN, pos))->ch != EQU_CH)
1967 pos++;
1968 while (pos < a->len && ((DIFFLN *) & g_array_index (a, DIFFLN, pos))->ch == EQU_CH)
1969 pos++;
1970 return pos;
1973 /* --------------------------------------------------------------------------------------------- */
1975 * Find start and end lines of the current hunk.
1977 * @param dview WDiff widget
1978 * @returns boolean and
1979 * start_line1 first line of current hunk (file[0])
1980 * end_line1 last line of current hunk (file[0])
1981 * start_line1 first line of current hunk (file[0])
1982 * end_line1 last line of current hunk (file[0])
1985 static int
1986 get_current_hunk (WDiff * dview, int *start_line1, int *end_line1, int *start_line2, int *end_line2)
1988 const GArray *a0 = dview->a[DIFF_LEFT];
1989 const GArray *a1 = dview->a[DIFF_RIGHT];
1990 size_t pos;
1991 int ch;
1992 int res = 0;
1994 *start_line1 = 1;
1995 *start_line2 = 1;
1996 *end_line1 = 1;
1997 *end_line2 = 1;
1999 pos = dview->skip_rows;
2000 ch = ((DIFFLN *) & g_array_index (a0, DIFFLN, pos))->ch;
2001 if (ch != EQU_CH)
2003 switch (ch)
2005 case ADD_CH:
2006 res = DIFF_DEL;
2007 break;
2008 case DEL_CH:
2009 res = DIFF_ADD;
2010 break;
2011 case CHG_CH:
2012 res = DIFF_CHG;
2013 break;
2015 while (pos > 0 && ((DIFFLN *) & g_array_index (a0, DIFFLN, pos))->ch != EQU_CH)
2016 pos--;
2017 if (pos > 0)
2019 *start_line1 = ((DIFFLN *) & g_array_index (a0, DIFFLN, pos))->line + 1;
2020 *start_line2 = ((DIFFLN *) & g_array_index (a1, DIFFLN, pos))->line + 1;
2022 pos = dview->skip_rows;
2023 while (pos < a0->len && ((DIFFLN *) & g_array_index (a0, DIFFLN, pos))->ch != EQU_CH)
2025 int l0, l1;
2027 l0 = ((DIFFLN *) & g_array_index (a0, DIFFLN, pos))->line;
2028 l1 = ((DIFFLN *) & g_array_index (a1, DIFFLN, pos))->line;
2029 if (l0 > 0)
2030 *end_line1 = max (*start_line1, l0);
2031 if (l1 > 0)
2032 *end_line2 = max (*start_line2, l1);
2033 pos++;
2036 return res;
2039 /* --------------------------------------------------------------------------------------------- */
2041 * Remove hunk from file.
2043 * @param dview WDiff widget
2044 * @param merge_file file stream for writing data
2045 * @param from1 first line of hunk
2046 * @param to1 last line of hunk
2047 * @param merge_direction in what direction files should be merged
2050 static void
2051 dview_remove_hunk (WDiff * dview, FILE * merge_file, int from1, int to1,
2052 action_direction_t merge_direction)
2054 int line;
2055 char buf[BUF_10K];
2056 FILE *f0;
2058 if (merge_direction == FROM_RIGHT_TO_LEFT)
2059 f0 = fopen (dview->file[DIFF_RIGHT], "r");
2060 else
2061 f0 = fopen (dview->file[DIFF_LEFT], "r");
2063 line = 0;
2064 while (fgets (buf, sizeof (buf), f0) != NULL && line < from1 - 1)
2066 line++;
2067 fputs (buf, merge_file);
2069 while (fgets (buf, sizeof (buf), f0) != NULL)
2071 line++;
2072 if (line >= to1)
2073 fputs (buf, merge_file);
2075 fclose (f0);
2078 /* --------------------------------------------------------------------------------------------- */
2080 * Add hunk to file.
2082 * @param dview WDiff widget
2083 * @param merge_file file stream for writing data
2084 * @param from1 first line of source hunk
2085 * @param from2 first line of destination hunk
2086 * @param to1 last line of source hunk
2087 * @param merge_direction in what direction files should be merged
2090 static void
2091 dview_add_hunk (WDiff * dview, FILE * merge_file, int from1, int from2, int to2,
2092 action_direction_t merge_direction)
2094 int line;
2095 char buf[BUF_10K];
2096 FILE *f0;
2097 FILE *f1;
2099 if (merge_direction == FROM_RIGHT_TO_LEFT)
2101 f0 = fopen (dview->file[DIFF_RIGHT], "r");
2102 f1 = fopen (dview->file[DIFF_LEFT], "r");
2104 else
2106 f0 = fopen (dview->file[DIFF_LEFT], "r");
2107 f1 = fopen (dview->file[DIFF_RIGHT], "r");
2110 line = 0;
2111 while (fgets (buf, sizeof (buf), f0) != NULL && line < from1 - 1)
2113 line++;
2114 fputs (buf, merge_file);
2116 line = 0;
2117 while (fgets (buf, sizeof (buf), f1) != NULL && line <= to2)
2119 line++;
2120 if (line >= from2)
2121 fputs (buf, merge_file);
2123 while (fgets (buf, sizeof (buf), f0) != NULL)
2124 fputs (buf, merge_file);
2126 fclose (f0);
2127 fclose (f1);
2130 /* --------------------------------------------------------------------------------------------- */
2132 * Replace hunk in file.
2134 * @param dview WDiff widget
2135 * @param merge_file file stream for writing data
2136 * @param from1 first line of source hunk
2137 * @param to1 last line of source hunk
2138 * @param from2 first line of destination hunk
2139 * @param to2 last line of destination hunk
2140 * @param merge_direction in what direction files should be merged
2143 static void
2144 dview_replace_hunk (WDiff * dview, FILE * merge_file, int from1, int to1, int from2, int to2,
2145 action_direction_t merge_direction)
2147 int line1 = 0, line2 = 0;
2148 char buf[BUF_10K];
2149 FILE *f0;
2150 FILE *f1;
2152 if (merge_direction == FROM_RIGHT_TO_LEFT)
2154 f0 = fopen (dview->file[DIFF_RIGHT], "r");
2155 f1 = fopen (dview->file[DIFF_LEFT], "r");
2157 else
2159 f0 = fopen (dview->file[DIFF_LEFT], "r");
2160 f1 = fopen (dview->file[DIFF_RIGHT], "r");
2163 while (fgets (buf, sizeof (buf), f0) != NULL && line1 < from1 - 1)
2165 line1++;
2166 fputs (buf, merge_file);
2168 while (fgets (buf, sizeof (buf), f1) != NULL && line2 <= to2)
2170 line2++;
2171 if (line2 >= from2)
2172 fputs (buf, merge_file);
2174 while (fgets (buf, sizeof (buf), f0) != NULL)
2176 line1++;
2177 if (line1 > to1)
2178 fputs (buf, merge_file);
2180 fclose (f0);
2181 fclose (f1);
2184 /* --------------------------------------------------------------------------------------------- */
2186 * Merge hunk.
2188 * @param dview WDiff widget
2189 * @param merge_direction in what direction files should be merged
2192 static void
2193 do_merge_hunk (WDiff * dview, action_direction_t merge_direction)
2195 int from1, to1, from2, to2;
2196 int res;
2197 int hunk;
2198 diff_place_t n_merge = (merge_direction == FROM_RIGHT_TO_LEFT) ? DIFF_RIGHT : DIFF_LEFT;
2200 if (merge_direction == FROM_RIGHT_TO_LEFT)
2201 hunk = get_current_hunk (dview, &from2, &to2, &from1, &to1);
2202 else
2203 hunk = get_current_hunk (dview, &from1, &to1, &from2, &to2);
2205 if (hunk > 0)
2207 int merge_file_fd;
2208 FILE *merge_file;
2209 vfs_path_t *merge_file_name_vpath = NULL;
2211 if (!dview->merged[n_merge])
2213 dview->merged[n_merge] = mc_util_make_backup_if_possible (dview->file[n_merge], "~~~");
2214 if (!dview->merged[n_merge])
2216 message (D_ERROR, MSG_ERROR,
2217 _("Cannot create backup file\n%s%s\n%s"),
2218 dview->file[n_merge], "~~~", unix_error_string (errno));
2219 return;
2223 merge_file_fd = mc_mkstemps (&merge_file_name_vpath, "mcmerge", NULL);
2224 if (merge_file_fd == -1)
2226 message (D_ERROR, MSG_ERROR, _("Cannot create temporary merge file\n%s"),
2227 unix_error_string (errno));
2228 return;
2231 merge_file = fdopen (merge_file_fd, "w");
2233 switch (hunk)
2235 case DIFF_DEL:
2236 if (merge_direction == FROM_RIGHT_TO_LEFT)
2237 dview_add_hunk (dview, merge_file, from1, from2, to2, FROM_RIGHT_TO_LEFT);
2238 else
2239 dview_remove_hunk (dview, merge_file, from1, to1, FROM_LEFT_TO_RIGHT);
2240 break;
2241 case DIFF_ADD:
2242 if (merge_direction == FROM_RIGHT_TO_LEFT)
2243 dview_remove_hunk (dview, merge_file, from1, to1, FROM_RIGHT_TO_LEFT);
2244 else
2245 dview_add_hunk (dview, merge_file, from1, from2, to2, FROM_LEFT_TO_RIGHT);
2246 break;
2247 case DIFF_CHG:
2248 dview_replace_hunk (dview, merge_file, from1, to1, from2, to2, merge_direction);
2249 break;
2251 fflush (merge_file);
2252 fclose (merge_file);
2253 res = rewrite_backup_content (merge_file_name_vpath, dview->file[n_merge]);
2254 mc_unlink (merge_file_name_vpath);
2255 vfs_path_free (merge_file_name_vpath);
2259 /* --------------------------------------------------------------------------------------------- */
2260 /* view routines and callbacks ********************************************** */
2262 static void
2263 dview_compute_split (WDiff * dview, int i)
2265 dview->bias += i;
2266 if (dview->bias < 2 - dview->half1)
2267 dview->bias = 2 - dview->half1;
2268 if (dview->bias > dview->half2 - 2)
2269 dview->bias = dview->half2 - 2;
2272 /* --------------------------------------------------------------------------------------------- */
2274 static void
2275 dview_compute_areas (WDiff * dview)
2277 dview->height = LINES - 2;
2278 dview->half1 = COLS / 2;
2279 dview->half2 = COLS - dview->half1;
2281 dview_compute_split (dview, 0);
2284 /* --------------------------------------------------------------------------------------------- */
2286 static void
2287 dview_reread (WDiff * dview)
2289 int ndiff;
2291 destroy_hdiff (dview);
2292 if (dview->a[DIFF_LEFT] != NULL)
2294 g_array_foreach (dview->a[DIFF_LEFT], DIFFLN, cc_free_elt);
2295 g_array_free (dview->a[DIFF_LEFT], TRUE);
2297 if (dview->a[DIFF_RIGHT] != NULL)
2299 g_array_foreach (dview->a[DIFF_RIGHT], DIFFLN, cc_free_elt);
2300 g_array_free (dview->a[DIFF_RIGHT], TRUE);
2303 dview->a[DIFF_LEFT] = g_array_new (FALSE, FALSE, sizeof (DIFFLN));
2304 dview->a[DIFF_RIGHT] = g_array_new (FALSE, FALSE, sizeof (DIFFLN));
2306 ndiff = redo_diff (dview);
2307 if (ndiff >= 0)
2308 dview->ndiff = ndiff;
2311 /* --------------------------------------------------------------------------------------------- */
2313 #ifdef HAVE_CHARSET
2314 static void
2315 dview_set_codeset (WDiff * dview)
2317 const char *encoding_id = NULL;
2319 dview->utf8 = TRUE;
2320 encoding_id =
2321 get_codepage_id (mc_global.source_codepage >=
2322 0 ? mc_global.source_codepage : mc_global.display_codepage);
2323 if (encoding_id != NULL)
2325 GIConv conv;
2327 conv = str_crt_conv_from (encoding_id);
2328 if (conv != INVALID_CONV)
2330 if (dview->converter != str_cnv_from_term)
2331 str_close_conv (dview->converter);
2332 dview->converter = conv;
2334 dview->utf8 = (gboolean) str_isutf8 (encoding_id);
2338 /* --------------------------------------------------------------------------------------------- */
2340 static void
2341 dview_select_encoding (WDiff * dview)
2343 if (do_select_codepage ())
2344 dview_set_codeset (dview);
2345 dview_reread (dview);
2346 tty_touch_screen ();
2347 repaint_screen ();
2349 #endif /* HAVE_CHARSET */
2351 /* --------------------------------------------------------------------------------------------- */
2353 static void
2354 dview_diff_options (WDiff * dview)
2356 const char *quality_str[] = {
2357 N_("No&rmal"),
2358 N_("&Fastest (Assume large files)"),
2359 N_("&Minimal (Find a smaller set of change)")
2362 QuickWidget diffopt_widgets[] = {
2363 QUICK_BUTTON (6, 10, 14, OPTY, N_("&Cancel"), B_CANCEL, NULL),
2364 QUICK_BUTTON (2, 10, 14, OPTY, N_("&OK"), B_ENTER, NULL),
2366 QUICK_CHECKBOX (3, OPTX, 12, OPTY,
2367 N_("Strip &trailing carriage return"), &dview->opt.strip_trailing_cr),
2368 QUICK_CHECKBOX (3, OPTX, 11, OPTY,
2369 N_("Ignore all &whitespace"), &dview->opt.ignore_all_space),
2370 QUICK_CHECKBOX (3, OPTX, 10, OPTY,
2371 N_("Ignore &space change"), &dview->opt.ignore_space_change),
2372 QUICK_CHECKBOX (3, OPTX, 9, OPTY,
2373 N_("Ignore tab &expansion"), &dview->opt.ignore_tab_expansion),
2374 QUICK_CHECKBOX (3, OPTX, 8, OPTY,
2375 N_("&Ignore case"), &dview->opt.ignore_case),
2376 QUICK_LABEL (3, OPTX, 7, OPTY, N_("Diff extra options")),
2377 QUICK_RADIO (3, OPTX, 3, OPTY,
2378 3, (const char **) quality_str, (int *) &dview->opt.quality),
2379 QUICK_LABEL (3, OPTX, 2, OPTY, N_("Diff algorithm")),
2381 QUICK_END
2384 QuickDialog diffopt = {
2385 OPTX, OPTY, -1, -1,
2386 N_("Diff Options"), "[Diff Options]",
2387 diffopt_widgets, NULL, NULL, FALSE
2390 if (quick_dialog (&diffopt) != B_CANCEL)
2391 dview_reread (dview);
2394 /* --------------------------------------------------------------------------------------------- */
2396 static int
2397 dview_init (WDiff * dview, const char *args, const char *file1, const char *file2,
2398 const char *label1, const char *label2, DSRC dsrc)
2400 int ndiff;
2401 FBUF *f[DIFF_COUNT];
2403 f[DIFF_LEFT] = NULL;
2404 f[DIFF_RIGHT] = NULL;
2406 if (dsrc == DATA_SRC_TMP)
2408 f[DIFF_LEFT] = f_temp ();
2409 if (f[DIFF_LEFT] == NULL)
2410 return -1;
2412 f[DIFF_RIGHT] = f_temp ();
2413 if (f[DIFF_RIGHT] == NULL)
2415 f_close (f[DIFF_LEFT]);
2416 return -1;
2419 else if (dsrc == DATA_SRC_ORG)
2421 f[DIFF_LEFT] = f_open (file1, O_RDONLY);
2422 if (f[DIFF_LEFT] == NULL)
2423 return -1;
2425 f[DIFF_RIGHT] = f_open (file2, O_RDONLY);
2426 if (f[DIFF_RIGHT] == NULL)
2428 f_close (f[DIFF_LEFT]);
2429 return -1;
2433 dview->args = args;
2434 dview->file[DIFF_LEFT] = file1;
2435 dview->file[DIFF_RIGHT] = file2;
2436 dview->label[DIFF_LEFT] = g_strdup (label1);
2437 dview->label[DIFF_RIGHT] = g_strdup (label2);
2438 dview->f[DIFF_LEFT] = f[0];
2439 dview->f[DIFF_RIGHT] = f[1];
2440 dview->merged[DIFF_LEFT] = FALSE;
2441 dview->merged[DIFF_RIGHT] = FALSE;
2442 dview->hdiff = NULL;
2443 dview->dsrc = dsrc;
2444 dview->converter = str_cnv_from_term;
2445 #ifdef HAVE_CHARSET
2446 dview_set_codeset (dview);
2447 #endif
2448 dview->a[DIFF_LEFT] = g_array_new (FALSE, FALSE, sizeof (DIFFLN));
2449 dview->a[DIFF_RIGHT] = g_array_new (FALSE, FALSE, sizeof (DIFFLN));
2451 ndiff = redo_diff (dview);
2452 if (ndiff < 0)
2454 /* goto WIDGET_DESTROY stage: dview_fini() */
2455 f_close (f[DIFF_LEFT]);
2456 f_close (f[DIFF_RIGHT]);
2457 return -1;
2460 dview->ndiff = ndiff;
2462 dview->view_quit = 0;
2464 dview->bias = 0;
2465 dview->new_frame = 1;
2466 dview->skip_rows = 0;
2467 dview->skip_cols = 0;
2468 dview->display_symbols = 0;
2469 dview->display_numbers = 0;
2470 dview->show_cr = 1;
2471 dview->tab_size = 8;
2472 dview->ord = DIFF_LEFT;
2473 dview->full = 0;
2475 dview->search.handle = NULL;
2476 dview->search.last_string = NULL;
2477 dview->search.last_found_line = -1;
2478 dview->search.last_accessed_num_line = -1;
2480 dview->opt.quality = 0;
2481 dview->opt.strip_trailing_cr = 0;
2482 dview->opt.ignore_tab_expansion = 0;
2483 dview->opt.ignore_space_change = 0;
2484 dview->opt.ignore_all_space = 0;
2485 dview->opt.ignore_case = 0;
2487 dview_compute_areas (dview);
2489 return 0;
2492 /* --------------------------------------------------------------------------------------------- */
2494 static void
2495 dview_fini (WDiff * dview)
2497 if (dview->dsrc != DATA_SRC_MEM)
2499 f_close (dview->f[DIFF_RIGHT]);
2500 f_close (dview->f[DIFF_LEFT]);
2503 if (dview->converter != str_cnv_from_term)
2504 str_close_conv (dview->converter);
2506 destroy_hdiff (dview);
2507 if (dview->a[DIFF_LEFT] != NULL)
2509 g_array_foreach (dview->a[DIFF_LEFT], DIFFLN, cc_free_elt);
2510 g_array_free (dview->a[DIFF_LEFT], TRUE);
2511 dview->a[DIFF_LEFT] = NULL;
2513 if (dview->a[DIFF_RIGHT] != NULL)
2515 g_array_foreach (dview->a[DIFF_RIGHT], DIFFLN, cc_free_elt);
2516 g_array_free (dview->a[DIFF_RIGHT], TRUE);
2517 dview->a[DIFF_RIGHT] = NULL;
2520 g_free (dview->label[DIFF_LEFT]);
2521 g_free (dview->label[DIFF_RIGHT]);
2524 /* --------------------------------------------------------------------------------------------- */
2526 static int
2527 dview_display_file (const WDiff * dview, diff_place_t ord, int r, int c, int height, int width)
2529 size_t i, k;
2530 int j;
2531 char buf[BUFSIZ];
2532 FBUF *f = dview->f[ord];
2533 int skip = dview->skip_cols;
2534 int display_symbols = dview->display_symbols;
2535 int display_numbers = dview->display_numbers;
2536 int show_cr = dview->show_cr;
2537 int tab_size = 8;
2538 const DIFFLN *p;
2539 int nwidth = display_numbers;
2540 int xwidth;
2542 xwidth = display_symbols + display_numbers;
2543 if (dview->tab_size > 0 && dview->tab_size < 9)
2544 tab_size = dview->tab_size;
2546 if (xwidth != 0)
2548 if (xwidth > width && display_symbols)
2550 xwidth--;
2551 display_symbols = 0;
2553 if (xwidth > width && display_numbers)
2555 xwidth = width;
2556 display_numbers = width;
2559 xwidth++;
2560 c += xwidth;
2561 width -= xwidth;
2562 if (width < 0)
2563 width = 0;
2566 if ((int) sizeof (buf) <= width || (int) sizeof (buf) <= nwidth)
2568 /* abnormal, but avoid buffer overflow */
2569 return -1;
2572 for (i = dview->skip_rows, j = 0; i < dview->a[ord]->len && j < height; j++, i++)
2574 int ch, next_ch, col;
2575 size_t cnt;
2577 p = (DIFFLN *) & g_array_index (dview->a[ord], DIFFLN, i);
2578 ch = p->ch;
2579 tty_setcolor (NORMAL_COLOR);
2580 if (display_symbols)
2582 tty_gotoyx (r + j, c - 2);
2583 tty_print_char (ch);
2585 if (p->line != 0)
2587 if (display_numbers)
2589 tty_gotoyx (r + j, c - xwidth);
2590 g_snprintf (buf, display_numbers + 1, "%*d", nwidth, p->line);
2591 tty_print_string (str_fit_to_term (buf, nwidth, J_LEFT_FIT));
2593 if (ch == ADD_CH)
2594 tty_setcolor (DFF_ADD_COLOR);
2595 if (ch == CHG_CH)
2596 tty_setcolor (DFF_CHG_COLOR);
2597 if (f == NULL)
2599 if (i == (size_t) dview->search.last_found_line)
2600 tty_setcolor (MARKED_SELECTED_COLOR);
2601 else if (dview->hdiff != NULL && g_ptr_array_index (dview->hdiff, i) != NULL)
2603 char att[BUFSIZ];
2605 if (dview->utf8)
2606 k = dview_str_utf8_offset_to_pos (p->p, width);
2607 else
2608 k = width;
2610 cvt_mgeta (p->p, p->u.len, buf, k, skip, tab_size, show_cr,
2611 g_ptr_array_index (dview->hdiff, i), ord, att);
2612 tty_gotoyx (r + j, c);
2613 col = 0;
2615 for (cnt = 0; cnt < strlen (buf) && col < width; cnt++)
2617 int w;
2618 gboolean ch_res;
2620 if (dview->utf8)
2622 next_ch = dview_get_utf (buf + cnt, &w, &ch_res);
2623 if (w > 1)
2624 cnt += w - 1;
2625 if (!g_unichar_isprint (next_ch))
2626 next_ch = '.';
2628 else
2629 next_ch = dview_get_byte (buf + cnt, &ch_res);
2631 if (ch_res)
2633 tty_setcolor (att[cnt] ? DFF_CHH_COLOR : DFF_CHG_COLOR);
2634 #ifdef HAVE_CHARSET
2635 if (mc_global.utf8_display)
2637 if (!dview->utf8)
2639 next_ch =
2640 convert_from_8bit_to_utf_c ((unsigned char) next_ch,
2641 dview->converter);
2644 else if (dview->utf8)
2645 next_ch = convert_from_utf_to_current_c (next_ch, dview->converter);
2646 else
2647 next_ch = convert_to_display_c (next_ch);
2648 #endif
2649 tty_print_anychar (next_ch);
2650 col++;
2653 continue;
2656 if (ch == CHG_CH)
2657 tty_setcolor (DFF_CHH_COLOR);
2659 if (dview->utf8)
2660 k = dview_str_utf8_offset_to_pos (p->p, width);
2661 else
2662 k = width;
2663 cvt_mget (p->p, p->u.len, buf, k, skip, tab_size, show_cr);
2665 else
2666 cvt_fget (f, p->u.off, buf, width, skip, tab_size, show_cr);
2668 else
2670 if (display_numbers)
2672 tty_gotoyx (r + j, c - xwidth);
2673 memset (buf, ' ', display_numbers);
2674 buf[display_numbers] = '\0';
2675 tty_print_string (buf);
2677 if (ch == DEL_CH)
2678 tty_setcolor (DFF_DEL_COLOR);
2679 if (ch == CHG_CH)
2680 tty_setcolor (DFF_CHD_COLOR);
2681 memset (buf, ' ', width);
2682 buf[width] = '\0';
2684 tty_gotoyx (r + j, c);
2685 /* tty_print_nstring (buf, width); */
2686 col = 0;
2687 for (cnt = 0; cnt < strlen (buf) && col < width; cnt++)
2689 int w;
2690 gboolean ch_res;
2692 if (dview->utf8)
2694 next_ch = dview_get_utf (buf + cnt, &w, &ch_res);
2695 if (w > 1)
2696 cnt += w - 1;
2697 if (!g_unichar_isprint (next_ch))
2698 next_ch = '.';
2700 else
2701 next_ch = dview_get_byte (buf + cnt, &ch_res);
2702 if (ch_res)
2704 #ifdef HAVE_CHARSET
2705 if (mc_global.utf8_display)
2707 if (!dview->utf8)
2709 next_ch =
2710 convert_from_8bit_to_utf_c ((unsigned char) next_ch, dview->converter);
2713 else if (dview->utf8)
2714 next_ch = convert_from_utf_to_current_c (next_ch, dview->converter);
2715 else
2716 next_ch = convert_to_display_c (next_ch);
2717 #endif
2719 tty_print_anychar (next_ch);
2720 col++;
2724 tty_setcolor (NORMAL_COLOR);
2725 k = width;
2726 if (width < xwidth - 1)
2727 k = xwidth - 1;
2728 memset (buf, ' ', k);
2729 buf[k] = '\0';
2730 for (; j < height; j++)
2732 if (xwidth != 0)
2734 tty_gotoyx (r + j, c - xwidth);
2735 /* tty_print_nstring (buf, xwidth - 1); */
2736 tty_print_string (str_fit_to_term (buf, xwidth - 1, J_LEFT_FIT));
2738 tty_gotoyx (r + j, c);
2739 /* tty_print_nstring (buf, width); */
2740 tty_print_string (str_fit_to_term (buf, width, J_LEFT_FIT));
2743 return 0;
2746 /* --------------------------------------------------------------------------------------------- */
2748 static void
2749 dview_status (const WDiff * dview, diff_place_t ord, int width, int c)
2751 const char *buf;
2752 int filename_width;
2753 int linenum, lineofs;
2754 vfs_path_t *vpath;
2755 char *path;
2757 tty_setcolor (STATUSBAR_COLOR);
2759 tty_gotoyx (0, c);
2760 get_line_numbers (dview->a[ord], dview->skip_rows, &linenum, &lineofs);
2762 filename_width = width - 24;
2763 if (filename_width < 8)
2764 filename_width = 8;
2766 vpath = vfs_path_from_str (dview->label[ord]);
2767 path = vfs_path_to_str_flags (vpath, 0, VPF_STRIP_HOME | VPF_STRIP_PASSWORD);
2768 vfs_path_free (vpath);
2769 buf = str_term_trim (path, filename_width);
2770 if (ord == DIFF_LEFT)
2771 tty_printf ("%s%-*s %6d+%-4d Col %-4d ", dview->merged[ord] ? "* " : " ", filename_width,
2772 buf, linenum, lineofs, dview->skip_cols);
2773 else
2774 tty_printf ("%s%-*s %6d+%-4d Dif %-4d ", dview->merged[ord] ? "* " : " ", filename_width,
2775 buf, linenum, lineofs, dview->ndiff);
2776 g_free (path);
2779 /* --------------------------------------------------------------------------------------------- */
2781 static void
2782 dview_redo (WDiff * dview)
2784 if (dview->display_numbers)
2786 int old;
2788 old = dview->display_numbers;
2789 dview->display_numbers = calc_nwidth ((const GArray **) dview->a);
2790 dview->new_frame = (old != dview->display_numbers);
2792 dview_reread (dview);
2795 /* --------------------------------------------------------------------------------------------- */
2797 static void
2798 dview_update (WDiff * dview)
2800 int height = dview->height;
2801 int width1;
2802 int width2;
2803 int last;
2805 last = dview->a[DIFF_LEFT]->len - 1;
2807 if (dview->skip_rows > last)
2808 dview->skip_rows = dview->search.last_accessed_num_line = last;
2809 if (dview->skip_rows < 0)
2810 dview->skip_rows = dview->search.last_accessed_num_line = 0;
2811 if (dview->skip_cols < 0)
2812 dview->skip_cols = 0;
2814 if (height < 2)
2815 return;
2817 width1 = dview->half1 + dview->bias;
2818 width2 = dview->half2 - dview->bias;
2819 if (dview->full)
2821 width1 = COLS;
2822 width2 = 0;
2825 if (dview->new_frame)
2827 int xwidth;
2829 tty_setcolor (NORMAL_COLOR);
2830 xwidth = dview->display_symbols + dview->display_numbers;
2831 if (width1 > 1)
2832 tty_draw_box (1, 0, height, width1, FALSE);
2833 if (width2 > 1)
2834 tty_draw_box (1, width1, height, width2, FALSE);
2836 if (xwidth != 0)
2838 xwidth++;
2839 if (xwidth < width1 - 1)
2841 tty_gotoyx (1, xwidth);
2842 tty_print_alt_char (mc_tty_frm[MC_TTY_FRM_DTOPMIDDLE], FALSE);
2843 tty_gotoyx (height, xwidth);
2844 tty_print_alt_char (mc_tty_frm[MC_TTY_FRM_DBOTTOMMIDDLE], FALSE);
2845 tty_draw_vline (2, xwidth, mc_tty_frm[MC_TTY_FRM_VERT], height - 2);
2847 if (xwidth < width2 - 1)
2849 tty_gotoyx (1, width1 + xwidth);
2850 tty_print_alt_char (mc_tty_frm[MC_TTY_FRM_DTOPMIDDLE], FALSE);
2851 tty_gotoyx (height, width1 + xwidth);
2852 tty_print_alt_char (mc_tty_frm[MC_TTY_FRM_DBOTTOMMIDDLE], FALSE);
2853 tty_draw_vline (2, width1 + xwidth, mc_tty_frm[MC_TTY_FRM_VERT], height - 2);
2856 dview->new_frame = 0;
2859 if (width1 > 2)
2861 dview_status (dview, dview->ord, width1, 0);
2862 dview_display_file (dview, dview->ord, 2, 1, height - 2, width1 - 2);
2864 if (width2 > 2)
2866 dview_status (dview, dview->ord ^ 1, width2, width1);
2867 dview_display_file (dview, dview->ord ^ 1, 2, width1 + 1, height - 2, width2 - 2);
2871 /* --------------------------------------------------------------------------------------------- */
2873 static void
2874 dview_edit (WDiff * dview, diff_place_t ord)
2876 Dlg_head *h;
2877 gboolean h_modal;
2878 int linenum, lineofs;
2880 if (dview->dsrc == DATA_SRC_TMP)
2882 error_dialog (_("Edit"), _("Edit is disabled"));
2883 return;
2886 h = ((Widget *) dview)->owner;
2887 h_modal = h->modal;
2889 get_line_numbers (dview->a[ord], dview->skip_rows, &linenum, &lineofs);
2890 h->modal = TRUE; /* not allow edit file in several editors */
2892 vfs_path_t *tmp_vpath;
2894 tmp_vpath = vfs_path_from_str (dview->file[ord]);
2895 do_edit_at_line (tmp_vpath, use_internal_edit, linenum);
2896 vfs_path_free (tmp_vpath);
2898 h->modal = h_modal;
2899 dview_redo (dview);
2900 dview_update (dview);
2903 /* --------------------------------------------------------------------------------------------- */
2905 static void
2906 dview_goto_cmd (WDiff * dview, diff_place_t ord)
2908 /* *INDENT-OFF* */
2909 static const char *title[2] = {
2910 N_("Goto line (left)"),
2911 N_("Goto line (right)")
2913 /* *INDENT-ON* */
2914 static char prev[256];
2915 /* XXX some statics here, to be remembered between runs */
2917 int newline;
2918 char *input;
2920 input = input_dialog (_(title[ord]), _("Enter line:"), MC_HISTORY_YDIFF_GOTO_LINE, prev);
2921 if (input != NULL)
2923 const char *s = input;
2925 if (scan_deci (&s, &newline) == 0 && *s == '\0')
2927 size_t i = 0;
2929 if (newline > 0)
2931 const DIFFLN *p;
2933 for (; i < dview->a[ord]->len; i++)
2935 p = &g_array_index (dview->a[ord], DIFFLN, i);
2936 if (p->line == newline)
2937 break;
2940 dview->skip_rows = dview->search.last_accessed_num_line = (ssize_t) i;
2941 g_snprintf (prev, sizeof (prev), "%d", newline);
2943 g_free (input);
2947 /* --------------------------------------------------------------------------------------------- */
2949 static void
2950 dview_labels (WDiff * dview)
2952 Dlg_head *h;
2953 WButtonBar *b;
2955 h = dview->widget.owner;
2956 b = find_buttonbar (h);
2958 buttonbar_set_label (b, 1, Q_ ("ButtonBar|Help"), diff_map, (Widget *) dview);
2959 buttonbar_set_label (b, 2, Q_ ("ButtonBar|Save"), diff_map, (Widget *) dview);
2960 buttonbar_set_label (b, 4, Q_ ("ButtonBar|Edit"), diff_map, (Widget *) dview);
2961 buttonbar_set_label (b, 5, Q_ ("ButtonBar|Merge"), diff_map, (Widget *) dview);
2962 buttonbar_set_label (b, 7, Q_ ("ButtonBar|Search"), diff_map, (Widget *) dview);
2963 buttonbar_set_label (b, 9, Q_ ("ButtonBar|Options"), diff_map, (Widget *) dview);
2964 buttonbar_set_label (b, 10, Q_ ("ButtonBar|Quit"), diff_map, (Widget *) dview);
2967 /* --------------------------------------------------------------------------------------------- */
2969 static int
2970 dview_event (Gpm_Event * event, void *data)
2972 WDiff *dview = (WDiff *) data;
2974 if (!mouse_global_in_widget (event, data))
2975 return MOU_UNHANDLED;
2977 /* We are not interested in release events */
2978 if ((event->type & (GPM_DOWN | GPM_DRAG)) == 0)
2979 return MOU_NORMAL;
2981 /* Wheel events */
2982 if ((event->buttons & GPM_B_UP) != 0 && (event->type & GPM_DOWN) != 0)
2984 dview->skip_rows -= 2;
2985 dview->search.last_accessed_num_line = dview->skip_rows;
2986 dview_update (dview);
2988 else if ((event->buttons & GPM_B_DOWN) != 0 && (event->type & GPM_DOWN) != 0)
2990 dview->skip_rows += 2;
2991 dview->search.last_accessed_num_line = dview->skip_rows;
2992 dview_update (dview);
2995 return MOU_NORMAL;
2998 /* --------------------------------------------------------------------------------------------- */
3000 static gboolean
3001 dview_save (WDiff * dview)
3003 gboolean res = TRUE;
3005 if (dview->merged[DIFF_LEFT])
3007 res = mc_util_unlink_backup_if_possible (dview->file[DIFF_LEFT], "~~~");
3008 dview->merged[DIFF_LEFT] = !res;
3010 if (dview->merged[DIFF_RIGHT])
3012 res = mc_util_unlink_backup_if_possible (dview->file[DIFF_RIGHT], "~~~");
3013 dview->merged[DIFF_RIGHT] = !res;
3015 return res;
3018 /* --------------------------------------------------------------------------------------------- */
3020 static void
3021 dview_do_save (WDiff * dview)
3023 (void) dview_save (dview);
3026 /* --------------------------------------------------------------------------------------------- */
3028 static void
3029 dview_save_options (WDiff * dview)
3031 mc_config_set_bool (mc_main_config, "DiffView", "show_symbols",
3032 dview->display_symbols != 0 ? TRUE : FALSE);
3033 mc_config_set_bool (mc_main_config, "DiffView", "show_numbers",
3034 dview->display_numbers != 0 ? TRUE : FALSE);
3035 mc_config_set_int (mc_main_config, "DiffView", "tab_size", dview->tab_size);
3037 mc_config_set_int (mc_main_config, "DiffView", "diff_quality", dview->opt.quality);
3039 mc_config_set_bool (mc_main_config, "DiffView", "diff_ignore_tws",
3040 dview->opt.strip_trailing_cr);
3041 mc_config_set_bool (mc_main_config, "DiffView", "diff_ignore_all_space",
3042 dview->opt.ignore_all_space);
3043 mc_config_set_bool (mc_main_config, "DiffView", "diff_ignore_space_change",
3044 dview->opt.ignore_space_change);
3045 mc_config_set_bool (mc_main_config, "DiffView", "diff_tab_expansion",
3046 dview->opt.ignore_tab_expansion);
3047 mc_config_set_bool (mc_main_config, "DiffView", "diff_ignore_case", dview->opt.ignore_case);
3050 /* --------------------------------------------------------------------------------------------- */
3052 static void
3053 dview_load_options (WDiff * dview)
3055 gboolean show_numbers, show_symbols;
3056 int tab_size;
3058 show_symbols = mc_config_get_bool (mc_main_config, "DiffView", "show_symbols", FALSE);
3059 if (show_symbols)
3060 dview->display_symbols = 1;
3061 show_numbers = mc_config_get_bool (mc_main_config, "DiffView", "show_numbers", FALSE);
3062 if (show_numbers)
3063 dview->display_numbers = calc_nwidth ((const GArray ** const) dview->a);
3064 tab_size = mc_config_get_int (mc_main_config, "DiffView", "tab_size", 8);
3065 if (tab_size > 0 && tab_size < 9)
3066 dview->tab_size = tab_size;
3067 else
3068 dview->tab_size = 8;
3070 dview->opt.quality = mc_config_get_int (mc_main_config, "DiffView", "diff_quality", 0);
3072 dview->opt.strip_trailing_cr =
3073 mc_config_get_bool (mc_main_config, "DiffView", "diff_ignore_tws", FALSE);
3074 dview->opt.ignore_all_space =
3075 mc_config_get_bool (mc_main_config, "DiffView", "diff_ignore_all_space", FALSE);
3076 dview->opt.ignore_space_change =
3077 mc_config_get_bool (mc_main_config, "DiffView", "diff_ignore_space_change", FALSE);
3078 dview->opt.ignore_tab_expansion =
3079 mc_config_get_bool (mc_main_config, "DiffView", "diff_tab_expansion", FALSE);
3080 dview->opt.ignore_case =
3081 mc_config_get_bool (mc_main_config, "DiffView", "diff_ignore_case", FALSE);
3083 dview->new_frame = 1;
3086 /* --------------------------------------------------------------------------------------------- */
3089 * Check if it's OK to close the diff viewer. If there are unsaved changes,
3090 * ask user.
3092 static gboolean
3093 dview_ok_to_exit (WDiff * dview)
3095 gboolean res = TRUE;
3096 int act;
3098 if (!dview->merged[DIFF_LEFT] && !dview->merged[DIFF_RIGHT])
3099 return res;
3101 act = query_dialog (_("Quit"), !mc_global.midnight_shutdown ?
3102 _("File(s) was modified. Save with exit?") :
3103 _("Midnight Commander is being shut down.\nSave modified file(s)?"),
3104 D_NORMAL, 2, _("&Yes"), _("&No"));
3106 /* Esc is No */
3107 if (mc_global.midnight_shutdown || (act == -1))
3108 act = 1;
3110 switch (act)
3112 case -1: /* Esc */
3113 res = FALSE;
3114 break;
3115 case 0: /* Yes */
3116 (void) dview_save (dview);
3117 res = TRUE;
3118 break;
3119 case 1: /* No */
3120 if (mc_util_restore_from_backup_if_possible (dview->file[DIFF_LEFT], "~~~"))
3121 res = mc_util_unlink_backup_if_possible (dview->file[DIFF_LEFT], "~~~");
3122 if (mc_util_restore_from_backup_if_possible (dview->file[DIFF_RIGHT], "~~~"))
3123 res = mc_util_unlink_backup_if_possible (dview->file[DIFF_RIGHT], "~~~");
3124 /* fall through */
3125 default:
3126 res = TRUE;
3127 break;
3129 return res;
3132 /* --------------------------------------------------------------------------------------------- */
3134 static cb_ret_t
3135 dview_execute_cmd (WDiff * dview, unsigned long command)
3137 cb_ret_t res = MSG_HANDLED;
3139 switch (command)
3141 case CK_ShowSymbols:
3142 dview->display_symbols ^= 1;
3143 dview->new_frame = 1;
3144 break;
3145 case CK_ShowNumbers:
3146 dview->display_numbers ^= calc_nwidth ((const GArray ** const) dview->a);
3147 dview->new_frame = 1;
3148 break;
3149 case CK_SplitFull:
3150 dview->full ^= 1;
3151 dview->new_frame = 1;
3152 break;
3153 case CK_SplitEqual:
3154 if (!dview->full)
3156 dview->bias = 0;
3157 dview->new_frame = 1;
3159 break;
3160 case CK_SplitMore:
3161 if (!dview->full)
3163 dview_compute_split (dview, 1);
3164 dview->new_frame = 1;
3166 break;
3168 case CK_SplitLess:
3169 if (!dview->full)
3171 dview_compute_split (dview, -1);
3172 dview->new_frame = 1;
3174 break;
3175 case CK_Tab2:
3176 dview->tab_size = 2;
3177 break;
3178 case CK_Tab3:
3179 dview->tab_size = 3;
3180 break;
3181 case CK_Tab4:
3182 dview->tab_size = 4;
3183 break;
3184 case CK_Tab8:
3185 dview->tab_size = 8;
3186 break;
3187 case CK_Swap:
3188 dview->ord ^= 1;
3189 break;
3190 case CK_Redo:
3191 dview_redo (dview);
3192 break;
3193 case CK_HunkNext:
3194 dview->skip_rows = dview->search.last_accessed_num_line =
3195 find_next_hunk (dview->a[DIFF_LEFT], dview->skip_rows);
3196 break;
3197 case CK_HunkPrev:
3198 dview->skip_rows = dview->search.last_accessed_num_line =
3199 find_prev_hunk (dview->a[DIFF_LEFT], dview->skip_rows);
3200 break;
3201 case CK_Goto:
3202 dview_goto_cmd (dview, TRUE);
3203 break;
3204 case CK_Edit:
3205 dview_edit (dview, dview->ord);
3206 break;
3207 case CK_Merge:
3208 do_merge_hunk (dview, FROM_LEFT_TO_RIGHT);
3209 dview_redo (dview);
3210 break;
3211 case CK_MergeOther:
3212 do_merge_hunk (dview, FROM_RIGHT_TO_LEFT);
3213 dview_redo (dview);
3214 break;
3215 case CK_EditOther:
3216 dview_edit (dview, dview->ord ^ 1);
3217 break;
3218 case CK_Search:
3219 dview_search_cmd (dview);
3220 break;
3221 case CK_SearchContinue:
3222 dview_continue_search_cmd (dview);
3223 break;
3224 case CK_Top:
3225 dview->skip_rows = dview->search.last_accessed_num_line = 0;
3226 break;
3227 case CK_Bottom:
3228 dview->skip_rows = dview->search.last_accessed_num_line = dview->a[DIFF_LEFT]->len - 1;
3229 break;
3230 case CK_Up:
3231 if (dview->skip_rows > 0)
3233 dview->skip_rows--;
3234 dview->search.last_accessed_num_line = dview->skip_rows;
3236 break;
3237 case CK_Down:
3238 dview->skip_rows++;
3239 dview->search.last_accessed_num_line = dview->skip_rows;
3240 break;
3241 case CK_PageDown:
3242 if (dview->height > 2)
3244 dview->skip_rows += dview->height - 2;
3245 dview->search.last_accessed_num_line = dview->skip_rows;
3247 break;
3248 case CK_PageUp:
3249 if (dview->height > 2)
3251 dview->skip_rows -= dview->height - 2;
3252 dview->search.last_accessed_num_line = dview->skip_rows;
3254 break;
3255 case CK_Left:
3256 dview->skip_cols--;
3257 break;
3258 case CK_Right:
3259 dview->skip_cols++;
3260 break;
3261 case CK_LeftQuick:
3262 dview->skip_cols -= 8;
3263 break;
3264 case CK_RightQuick:
3265 dview->skip_cols += 8;
3266 break;
3267 case CK_Home:
3268 dview->skip_cols = 0;
3269 break;
3270 case CK_Shell:
3271 view_other_cmd ();
3272 break;
3273 case CK_Quit:
3274 dview->view_quit = 1;
3275 break;
3276 case CK_Save:
3277 dview_do_save (dview);
3278 break;
3279 case CK_Options:
3280 dview_diff_options (dview);
3281 break;
3282 #ifdef HAVE_CHARSET
3283 case CK_SelectCodepage:
3284 dview_select_encoding (dview);
3285 break;
3286 #endif
3287 case CK_Cancel:
3288 /* don't close diffviewer due to SIGINT */
3289 break;
3290 default:
3291 res = MSG_NOT_HANDLED;
3293 return res;
3296 /* --------------------------------------------------------------------------------------------- */
3298 static cb_ret_t
3299 dview_handle_key (WDiff * dview, int key)
3301 unsigned long command;
3303 #ifdef HAVE_CHARSET
3304 key = convert_from_input_c (key);
3305 #endif
3307 command = keybind_lookup_keymap_command (diff_map, key);
3308 if ((command != CK_IgnoreKey) && (dview_execute_cmd (dview, command) == MSG_HANDLED))
3309 return MSG_HANDLED;
3311 /* Key not used */
3312 return MSG_NOT_HANDLED;
3315 /* --------------------------------------------------------------------------------------------- */
3317 static cb_ret_t
3318 dview_callback (Widget * w, widget_msg_t msg, int parm)
3320 WDiff *dview = (WDiff *) w;
3321 Dlg_head *h = dview->widget.owner;
3322 cb_ret_t i;
3324 switch (msg)
3326 case WIDGET_INIT:
3327 dview_labels (dview);
3328 dview_load_options (dview);
3329 dview_update (dview);
3330 return MSG_HANDLED;
3332 case WIDGET_DRAW:
3333 dview->new_frame = 1;
3334 dview_update (dview);
3335 return MSG_HANDLED;
3337 case WIDGET_KEY:
3338 i = dview_handle_key (dview, parm);
3339 if (dview->view_quit)
3340 dlg_stop (h);
3341 else
3342 dview_update (dview);
3343 return i;
3345 case WIDGET_COMMAND:
3346 i = dview_execute_cmd (dview, parm);
3347 if (dview->view_quit)
3348 dlg_stop (h);
3349 else
3350 dview_update (dview);
3351 return i;
3353 case WIDGET_DESTROY:
3354 dview_save_options (dview);
3355 dview_fini (dview);
3356 return MSG_HANDLED;
3358 default:
3359 return default_proc (msg, parm);
3363 /* --------------------------------------------------------------------------------------------- */
3365 static void
3366 dview_adjust_size (Dlg_head * h)
3368 WDiff *dview;
3369 WButtonBar *bar;
3371 /* Look up the viewer and the buttonbar, we assume only two widgets here */
3372 dview = (WDiff *) find_widget_type (h, dview_callback);
3373 bar = find_buttonbar (h);
3374 widget_set_size (&dview->widget, 0, 0, LINES - 1, COLS);
3375 widget_set_size ((Widget *) bar, LINES - 1, 0, 1, COLS);
3377 dview_compute_areas (dview);
3380 /* --------------------------------------------------------------------------------------------- */
3382 static cb_ret_t
3383 dview_dialog_callback (Dlg_head * h, Widget * sender, dlg_msg_t msg, int parm, void *data)
3385 WDiff *dview = (WDiff *) data;
3387 switch (msg)
3389 case DLG_RESIZE:
3390 dview_adjust_size (h);
3391 return MSG_HANDLED;
3393 case DLG_ACTION:
3394 /* shortcut */
3395 if (sender == NULL)
3396 return dview_execute_cmd (NULL, parm);
3397 /* message from buttonbar */
3398 if (sender == (Widget *) find_buttonbar (h))
3400 if (data != NULL)
3401 return send_message ((Widget *) data, WIDGET_COMMAND, parm);
3403 dview = (WDiff *) find_widget_type (h, dview_callback);
3404 return dview_execute_cmd (dview, parm);
3406 return MSG_NOT_HANDLED;
3408 case DLG_VALIDATE:
3409 dview = (WDiff *) find_widget_type (h, dview_callback);
3410 h->state = DLG_ACTIVE; /* don't stop the dialog before final decision */
3411 if (dview_ok_to_exit (dview))
3412 h->state = DLG_CLOSED;
3413 return MSG_HANDLED;
3415 default:
3416 return default_dlg_callback (h, sender, msg, parm, data);
3420 /* --------------------------------------------------------------------------------------------- */
3422 static char *
3423 dview_get_title (const Dlg_head * h, size_t len)
3425 const WDiff *dview;
3426 const char *modified = " (*) ";
3427 const char *notmodified = " ";
3428 size_t len1;
3429 GString *title;
3431 dview = (const WDiff *) find_widget_type (h, dview_callback);
3432 len1 = (len - str_term_width1 (_("Diff:")) - strlen (modified) - 3) / 2;
3434 title = g_string_sized_new (len);
3435 g_string_append (title, _("Diff:"));
3436 g_string_append (title, dview->merged[DIFF_LEFT] ? modified : notmodified);
3437 g_string_append (title, str_term_trim (dview->label[DIFF_LEFT], len1));
3438 g_string_append (title, " | ");
3439 g_string_append (title, dview->merged[DIFF_RIGHT] ? modified : notmodified);
3440 g_string_append (title, str_term_trim (dview->label[DIFF_RIGHT], len1));
3442 return g_string_free (title, FALSE);
3445 /* --------------------------------------------------------------------------------------------- */
3447 static int
3448 diff_view (const char *file1, const char *file2, const char *label1, const char *label2)
3450 int error;
3451 WDiff *dview;
3452 Dlg_head *dview_dlg;
3454 /* Create dialog and widgets, put them on the dialog */
3455 dview_dlg =
3456 create_dlg (FALSE, 0, 0, LINES, COLS, NULL, dview_dialog_callback, NULL,
3457 "[Diff Viewer]", NULL, DLG_WANT_TAB);
3459 dview = g_new0 (WDiff, 1);
3461 init_widget (&dview->widget, 0, 0, LINES - 1, COLS,
3462 (callback_fn) dview_callback, (mouse_h) dview_event);
3464 widget_want_cursor (dview->widget, 0);
3466 add_widget (dview_dlg, dview);
3467 add_widget (dview_dlg, buttonbar_new (TRUE));
3469 dview_dlg->get_title = dview_get_title;
3471 error = dview_init (dview, "-a", file1, file2, label1, label2, DATA_SRC_MEM); /* XXX binary diff? */
3473 /* Please note that if you add another widget,
3474 * you have to modify dview_adjust_size to
3475 * be aware of it
3477 if (error == 0)
3478 run_dlg (dview_dlg);
3480 if ((error != 0) || (dview_dlg->state == DLG_CLOSED))
3481 destroy_dlg (dview_dlg);
3483 return error == 0 ? 1 : 0;
3486 /*** public functions ****************************************************************************/
3487 /* --------------------------------------------------------------------------------------------- */
3489 #define GET_FILE_AND_STAMP(n) \
3490 do \
3492 use_copy##n = 0; \
3493 real_file##n = file##n; \
3494 if (!vfs_file_is_local (file##n)) \
3496 real_file##n = mc_getlocalcopy (file##n); \
3497 if (real_file##n != NULL) \
3499 use_copy##n = 1; \
3500 if (mc_stat (real_file##n, &st##n) != 0) \
3501 use_copy##n = -1; \
3505 while (0)
3507 #define UNGET_FILE(n) \
3508 do \
3510 if (use_copy##n) \
3512 int changed = 0; \
3513 if (use_copy##n > 0) \
3515 time_t mtime; \
3516 mtime = st##n.st_mtime; \
3517 if (mc_stat (real_file##n, &st##n) == 0) \
3518 changed = (mtime != st##n.st_mtime); \
3520 mc_ungetlocalcopy (file##n, real_file##n, changed); \
3521 vfs_path_free (real_file##n); \
3524 while (0)
3526 gboolean
3527 dview_diff_cmd (const void *f0, const void *f1)
3529 int rv = 0;
3530 vfs_path_t *file0 = NULL;
3531 vfs_path_t *file1 = NULL;
3532 gboolean is_dir0 = FALSE;
3533 gboolean is_dir1 = FALSE;
3535 switch (mc_global.mc_run_mode)
3537 case MC_RUN_FULL:
3539 /* run from panels */
3540 const WPanel *panel0 = (const WPanel *) f0;
3541 const WPanel *panel1 = (const WPanel *) f1;
3543 file0 = vfs_path_append_new (panel0->cwd_vpath, selection (panel0)->fname, NULL);
3544 is_dir0 = S_ISDIR (selection (panel0)->st.st_mode);
3545 if (is_dir0)
3547 message (D_ERROR, MSG_ERROR, _("\"%s\" is a directory"),
3548 path_trunc (selection (panel0)->fname, 30));
3549 goto ret;
3552 file1 = vfs_path_append_new (panel1->cwd_vpath, selection (panel1)->fname, NULL);
3553 is_dir1 = S_ISDIR (selection (panel1)->st.st_mode);
3554 if (is_dir1)
3556 message (D_ERROR, MSG_ERROR, _("\"%s\" is a directory"),
3557 path_trunc (selection (panel1)->fname, 30));
3558 goto ret;
3560 break;
3563 case MC_RUN_DIFFVIEWER:
3565 /* run from command line */
3566 const char *p0 = (const char *) f0;
3567 const char *p1 = (const char *) f1;
3568 struct stat st;
3570 file0 = vfs_path_from_str (p0);
3571 if (mc_stat (file0, &st) == 0)
3573 is_dir0 = S_ISDIR (st.st_mode);
3574 if (is_dir0)
3576 message (D_ERROR, MSG_ERROR, _("\"%s\" is a directory"), path_trunc (p0, 30));
3577 goto ret;
3580 else
3582 message (D_ERROR, MSG_ERROR, _("Cannot stat \"%s\"\n%s"),
3583 path_trunc (p0, 30), unix_error_string (errno));
3584 goto ret;
3587 file1 = vfs_path_from_str (p1);
3588 if (mc_stat (file1, &st) == 0)
3590 is_dir1 = S_ISDIR (st.st_mode);
3591 if (is_dir1)
3593 message (D_ERROR, MSG_ERROR, _("\"%s\" is a directory"), path_trunc (p1, 30));
3594 goto ret;
3597 else
3599 message (D_ERROR, MSG_ERROR, _("Cannot stat \"%s\"\n%s"),
3600 path_trunc (p1, 30), unix_error_string (errno));
3601 goto ret;
3603 break;
3606 default:
3607 /* this should not happaned */
3608 message (D_ERROR, MSG_ERROR, _("Diff viewer: invalid mode"));
3609 return FALSE;
3612 if (rv == 0)
3614 rv = -1;
3615 if (file0 != NULL && file1 != NULL)
3617 int use_copy0;
3618 int use_copy1;
3619 struct stat st0;
3620 struct stat st1;
3621 vfs_path_t *real_file0;
3622 vfs_path_t *real_file1;
3624 GET_FILE_AND_STAMP (0);
3625 GET_FILE_AND_STAMP (1);
3626 if (real_file0 != NULL && real_file1 != NULL)
3628 char *real_file0_str, *real_file1_str;
3629 char *file0_str, *file1_str;
3631 real_file0_str = vfs_path_to_str (real_file0);
3632 real_file1_str = vfs_path_to_str (real_file1);
3633 file0_str = vfs_path_to_str (file0);
3634 file1_str = vfs_path_to_str (file1);
3635 rv = diff_view (real_file0_str, real_file1_str, file0_str, file1_str);
3636 g_free (real_file0_str);
3637 g_free (real_file1_str);
3638 g_free (file0_str);
3639 g_free (file1_str);
3641 UNGET_FILE (1);
3642 UNGET_FILE (0);
3646 if (rv == 0)
3647 message (D_ERROR, MSG_ERROR, _("Two files are needed to compare"));
3649 ret:
3650 vfs_path_free (file1);
3651 vfs_path_free (file0);
3653 return (rv != 0);
3656 #undef GET_FILE_AND_STAMP
3657 #undef UNGET_FILE
3659 /* --------------------------------------------------------------------------------------------- */