Compare commits

..

16 Commits

Author SHA1 Message Date
sfraser%netscape.com
90db50a241 Rename DoDeleteSelectionTxn and DoInsertTextTxn to DeleteSelectionImpl and InsertTextImpl
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42713 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-08 23:01:41 +00:00
sfraser%netscape.com
b94ca96f67 Tidy up
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42584 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 23:28:34 +00:00
sfraser%netscape.com
dbc4ad9e23 Init some member variables, and add get/set text length
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42574 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 23:01:15 +00:00
sfraser%netscape.com
3362351bce Add text length getters and setters, and init some member variables
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42573 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 23:00:34 +00:00
sfraser%netscape.com
a5e80a7996 Editor API changes branch.
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42556 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 21:50:13 +00:00
sfraser%netscape.com
0d3d41abb6 Change name of delete direction enum values.
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42555 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 21:49:48 +00:00
sfraser%netscape.com
9306d36936 Fix direction enum, and to a QUI to the HTML editor for InsertText
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42554 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 21:48:52 +00:00
akkana%netscape.com
c8fc878e9a integrate plaintext paste/insert stuff
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42550 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 21:34:10 +00:00
akkana%netscape.com
e607ecc70c build editor logs only if ENABLE_JS_EDITOR_LOG is defined
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42549 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 21:33:43 +00:00
sfraser%netscape.com
70fad68ccb Changes to Init() to pass in the flags, and to the rules to accept flags in their ctors.
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42547 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 21:26:11 +00:00
sfraser%netscape.com
18a882fac8 Coupla #error directives
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42546 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 21:24:50 +00:00
sfraser%netscape.com
bb3d6764f1 Pass the editor flags into the rules
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42545 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 21:24:17 +00:00
sfraser%netscape.com
d05bf21df3 Make GetTextNodeTag public.
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42533 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 20:51:46 +00:00
sfraser%netscape.com
e55cb831f2 Editor API changes; breaking editor interfaces into more, non-overlapping interfaces, with internal reorg of editor classes.
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42517 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 20:22:53 +00:00
sfraser%netscape.com
700abcba2e First Checked In.
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42516 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-06 20:22:32 +00:00
(no author)
cf894201dd This commit was manufactured by cvs2svn to create branch 'EditorUI_BRANCH'.
git-svn-id: svn://10.0.0.236/branches/EditorUI_BRANCH@42142 18797224-902f-48f8-a5cc-f745e15eee43
1999-08-04 15:18:35 +00:00
369 changed files with 86419 additions and 9122 deletions

View File

@@ -1,80 +0,0 @@
#!perl
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Simon Fraser <sfraser@netscape.com>
#
require 5.004;
use strict;
use Cwd;
use Moz::BuildUtils;
use Moz::BuildCore;
#-------------------------------------------------------------
# Where have the build options gone?
#
# The various build flags have been centralized into one place.
# The master list of options is in MozBuildFlags.txt. However,
# you should never need to edit that file, or this one.
#
# To customize what gets built, or where to start the build,
# edit the $prefs_file_name file in
# System Folder:Preferences:Mozilla build prefs:
# Documentation is provided in that file.
#-------------------------------------------------------------
my($prefs_file_name) = "Mozilla opt build prefs";
my($config_header_file_name) = ":mozilla:config:mac:DefinesOptions.h";
#-------------------------------------------------------------
# hashes to hold build options
#-------------------------------------------------------------
my(%build);
my(%options);
my(%filepaths);
my(%optiondefines);
# Hash of input files for this build. Eventually, there will be
# input files for manifests, and projects too.
my(%inputfiles) = (
"buildflags", "MozillaBuildFlags.txt",
"checkoutdata", "MozillaCheckoutList.txt",
"buildprogress", "¥ Mozilla opt progress",
"buildmodule", "MozillaBuildList.pm",
"checkouttime", "Mozilla last checkout"
);
#-------------------------------------------------------------
# end build hashes
#-------------------------------------------------------------
# set the build root directory, which is the the dir above mozilla
SetupBuildRootDir(":mozilla:build:mac:build_scripts");
# Set up all the flags on $main::, like DEBUG, CARBON etc.
# Override the defaults using the preferences files.
SetupDefaultBuildOptions(0, ":mozilla:dist:viewer:", $config_header_file_name);
my($do_checkout) = 0;
my($do_build) = 1;
RunBuild($do_checkout, $do_build, \%inputfiles, $prefs_file_name);

View File

@@ -1,80 +0,0 @@
#!perl
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Simon Fraser <sfraser@netscape.com>
#
require 5.004;
use strict;
use Cwd;
use Moz::BuildUtils;
use Moz::BuildCore;
#-------------------------------------------------------------
# Where have the build options gone?
#
# The various build flags have been centralized into one place.
# The master list of options is in MozBuildFlags.txt. However,
# you should never need to edit that file, or this one.
#
# To customize what gets built, or where to start the build,
# edit the $prefs_file_name file in
# System Folder:Preferences:Mozilla build prefs:
# Documentation is provided in that file.
#-------------------------------------------------------------
my($prefs_file_name) = "Mozilla debug build prefs";
my($config_header_file_name) = ":mozilla:config:mac:DefinesOptionsDebug.h";
#-------------------------------------------------------------
# hashes to hold build options
#-------------------------------------------------------------
my(%build);
my(%options);
my(%filepaths);
my(%optiondefines);
# Hash of input files for this build. Eventually, there will be
# input files for manifests, and projects too.
my(%inputfiles) = (
"buildflags", "MozillaBuildFlags.txt",
"checkoutdata", "MozillaCheckoutList.txt",
"buildprogress", "¥ Mozilla debug progress",
"buildmodule", "MozillaBuildList.pm",
"checkouttime", "Mozilla last checkout"
);
#-------------------------------------------------------------
# end build hashes
#-------------------------------------------------------------
# set the build root directory, which is the the dir above mozilla
SetupBuildRootDir(":mozilla:build:mac:build_scripts");
# Set up all the flags on $main::, like DEBUG, CARBON etc.
# Override the defaults using the preferences files.
SetupDefaultBuildOptions(1, ":mozilla:dist:viewer_debug:", $config_header_file_name);
my($do_pull) = 0; # overridden by flags and prefs
my($do_build) = 1;
RunBuild($do_pull, $do_build, \%inputfiles, $prefs_file_name);

View File

@@ -1,595 +0,0 @@
#!perl -w
package Moz::BuildCore;
require 5.004;
require Exporter;
use strict;
use vars qw( @ISA @EXPORT );
# perl includes
use Cwd;
use POSIX;
use Time::Local;
use File::Basename;
use LWP::Simple;
# homegrown
use Moz::Moz;
use Moz::Jar;
use Moz::BuildFlags;
use Moz::BuildUtils;
use Moz::CodeWarriorLib;
# use MozillaBuildList; # eventually, this should go away, and be replaced by data input
@ISA = qw(Exporter);
@EXPORT = qw(
RunBuild
);
#//--------------------------------------------------------------------------------------------------
#// DoPrebuildCheck
#//
#// Check the build tools etc before running the build.
#//--------------------------------------------------------------------------------------------------
sub DoPrebuildCheck()
{
SanityCheckBuildOptions();
# launch codewarrior and persist its location. Have to call this before first
# call to getCodeWarriorPath().
my($ide_path_file) = $main::filepaths{"idepath"};
$ide_path_file = full_path_to($ide_path_file);
LaunchCodeWarrior($ide_path_file);
}
#//--------------------------------------------------------------------------------------------------
#// SanityCheckBuildOptions
#//--------------------------------------------------------------------------------------------------
sub SanityCheckBuildOptions()
{
my($bad_options) = 0;
# Jar options
if (!$main::options{chrome_jars} && !$main::options{chrome_files})
{
print "Warning: Both \$options{chrome_jars} and \$options{chrome_files} are off. You won't get any chrome.\n";
$bad_options = 1;
}
if (!$main::options{chrome_jars} && $main::options{use_jars})
{
print "Warning: \$options{chrome_jars} is off but \$options{use_jars} is on. Your build won't run (expects jars, got files).\n";
$bad_options = 1;
}
if (!$main::options{chrome_files} && !$main::options{use_jars})
{
print "Warning: \$options{chrome_jars} is off but \$options{chrome_files} is on. Your build won't run (expects files, got jars).\n";
$bad_options = 1;
}
if ($main::options{ldap_experimental} && !$main::options{ldap})
{
print "Warning: \$options{ldap_experimental} is on but \$options{ldap} is off. LDAP experimental features will not be built.\n";
$bad_options = 1;
}
if ($main::options{wsp} && !$main::options{xmlextras})
{
print "Warning: \$options{wsp} is on but \$options{xmlextras} is off. wsp will not be built.\n";
$bad_options = 1;
}
if ($bad_options) {
print "Build will start in 5 seconds. Press command-. to stop\n";
DelayFor(5);
}
}
#//--------------------------------------------------------------------------------------------------
#// GenBuildSystemInfo
#//--------------------------------------------------------------------------------------------------
sub GenBuildSystemInfo()
{
# always rebuild the configuration program.
BuildProjectClean(":mozilla:build:mac:tools:BuildSystemInfo:BuildSystemInfo.mcp", "BuildSystemInfo");
# delete the configuration file.
unlink(":mozilla:build:mac:BuildSystemInfo.pm");
# run the program.
system(":mozilla:build:mac:BuildSystemInfo");
# wait for the file to be created.
while (!(-e ":mozilla:build:mac:BuildSystemInfo.pm")) { WaitNextEvent(); }
# wait for BuildSystemInfo to finish, so that we see correct results.
while (IsProcessRunning("BuildSystemInfo")) { WaitNextEvent(); }
# now, evaluate the contents of the file.
open(F, ":mozilla:build:mac:BuildSystemInfo.pm");
while (<F>) { eval; }
close(F);
}
#//--------------------------------------------------------------------------------------------------
#// Make library aliases
#//--------------------------------------------------------------------------------------------------
sub MakeLibAliases()
{
my($dist_dir) = GetBinDirectory();
#// ProfilerLib
if ($main::PROFILE)
{
my($profilerlibpath) = Moz::CodeWarriorLib::getCodeWarriorPath("MacOS Support:Profiler:Profiler Common:ProfilerLib");
MakeAlias("$profilerlibpath", "$dist_dir"."Essential Files:");
}
}
#//--------------------------------------------------------------------------------------------------
#// ConfigureBuildSystem
#//
#// defines some build-system configuration variables.
#//--------------------------------------------------------------------------------------------------
sub ConfigureBuildSystem()
{
#// In the future, we may want to do configurations based on the actual build system itself.
#// GenBuildSystemInfo();
#// For now, if we discover a newer header file than existed in Universal Interfaces 3.2,
#// we'll assume that 3.3 or later is in use.
my($universal_interfaces) = Moz::CodeWarriorLib::getCodeWarriorPath("MacOS Support:Universal:Interfaces:CIncludes:");
if (-e ($universal_interfaces . "ControlDefinitions.h")) {
$main::UNIVERSAL_INTERFACES_VERSION = 0x0330;
}
#// Rename IC SDK folder in the Mac OS Support folder
my($ic_sdk_folder) = Moz::CodeWarriorLib::getCodeWarriorPath("MacOS Support:ICProgKit2.0.2");
if( -e $ic_sdk_folder)
{
my($new_ic_folder_name) = Moz::CodeWarriorLib::getCodeWarriorPath("MacOS Support:(ICProgKit2.0.2)");
rename ($ic_sdk_folder, $new_ic_folder_name);
# note that CodeWarrior doesn't descend into folders with () the name
print "Mozilla no longer needs the Internet Config SDK to build:\n Renaming the 'ICProgKit2.0.2' folder to '(ICProgKit2.0.2)'\n";
}
printf("UNIVERSAL_INTERFACES_VERSION = 0x%04X\n", $main::UNIVERSAL_INTERFACES_VERSION);
# alias required CodeWarrior libs into the Essential Files folder (only the Profiler lib now)
MakeLibAliases();
}
#//--------------------------------------------------------------------------------------------------
#// CheckOutModule. Takes variable number of args; first two are required
#//--------------------------------------------------------------------------------------------------
sub CheckOutModule($$$$)
{
my($session, $module, $revision, $date) = @_;
my($result) = $session->checkout($module, $revision, $date);
# result of 1 is success
if ($result) { return; }
my($checkout_err) = $session->getLastError();
if ($checkout_err == 708) {
die "Error: Checkout was cancelled.\n";
} elsif ($checkout_err == 911) {
die "Error: CVS session settings are incorrect. Check your password, and the CVS root settings.\n";
} elsif ($checkout_err == 703) {
die "Error: CVS checkout failed. Unknown module, unknown tag, bad username, or other CVS error.\n";
} elsif ($checkout_err == 711) {
print "Checkout of '$module' failed.\n";
}
}
#//--------------------------------------------------------------------------------------------------
#// getScriptFolder
#//--------------------------------------------------------------------------------------------------
sub getScriptFolder()
{
return dirname($0);
}
#//--------------------------------------------------------------------------------------------------
#// getScriptFolder
#//--------------------------------------------------------------------------------------------------
sub get_url_contents($)
{
my($url) = @_;
my($url_contents) = LWP::Simple::get($url);
$url_contents =~ s/\r\n/\n/g; # normalize linebreaks
$url_contents =~ s/\r/\n/g; # normalize linebreaks
return $url_contents;
}
#//--------------------------------------------------------------------------------------------------
#// get_files_from_content
#//--------------------------------------------------------------------------------------------------
sub uniq
{
my $lastval;
grep(($_ ne $lastval, $lastval = $_)[$[], @_);
}
#//--------------------------------------------------------------------------------------------------
#// get_files_from_content
#//--------------------------------------------------------------------------------------------------
sub get_files_from_content($)
{
my($content) = @_;
my(@jscalls) = grep (/return js_file_menu[^{]*/, split(/\n/, $content));
my $i;
for ($i = 0; $i < @jscalls ; $i++)
{
$jscalls[$i] =~ s/.*\(|\).*//g;
my(@callparams) = split(/,/, $jscalls[$i]);
my ($repos, $dir, $file, $rev) = grep(s/['\s]//g, @callparams);
$jscalls[$i] = "$dir/$file";
}
&uniq(sort(@jscalls));
}
#//--------------------------------------------------------------------------------------------------
#// getLastUpdateTime
#//
#// Get the last time we updated. Return 0 on failure
#//--------------------------------------------------------------------------------------------------
sub getLastUpdateTime($)
{
my($timestamp_file) = @_;
my($time_string);
local(*TIMESTAMP_FILE);
unless (open(TIMESTAMP_FILE, "< $timestamp_file")) { return 0; }
while (<TIMESTAMP_FILE>)
{
my($line) = $_;
chomp($line);
# ignore comments and empty lines
if ($line =~ /^\#/ || $line =~ /^\s*$/) {
next;
}
$time_string = $line;
}
# get the epoch seconds
my($last_update_secs) = $time_string;
$last_update_secs =~ s/\s#.+$//;
print "FAST_UPDATE found that you last updated at ".localtime($last_update_secs)."\n";
# how long ago was this, in hours?
my($gm_now) = time();
my($update_hours) = 1 + ceil(($gm_now - $last_update_secs) / (60 * 60));
return $update_hours;
}
#//--------------------------------------------------------------------------------------------------
#// saveCheckoutTimestamp
#//
#// Create a file on disk containing the current time. Param is time(), which is an Epoch seconds
#// (and therefore in GMT).
#//
#//--------------------------------------------------------------------------------------------------
sub saveCheckoutTimestamp($$)
{
my($gm_secs, $timestamp_file) = @_;
local(*TIMESTAMP_FILE);
open(TIMESTAMP_FILE, ">$timestamp_file") || die "Failed to open $timestamp_file\n";
print(TIMESTAMP_FILE "# time of last checkout or update, in GMT. Used by FAST_UPDATE\n");
print(TIMESTAMP_FILE "$gm_secs \# around ".localtime()." local time\n");
close(TIMESTAMP_FILE);
}
#//--------------------------------------------------------------------------------------------------
#// FastUpdate
#//
#// Use Bonsai url data to update only those dirs which have new files
#//
#//--------------------------------------------------------------------------------------------------
sub FastUpdate($$)
{
my($modules, $timestamp_file) = @_; # list of modules to check out
my($num_hours) = getLastUpdateTime($timestamp_file);
if ($num_hours == 0 || $num_hours > 170) {
print "Can't fast_update; last update was too long ago, or never. Doing normal checkout.\n";
return 0;
}
print "Doing fast update, pulling files changed in the last $num_hours hours\n";
my($cvsfile) = AskAndPersistFile($main::filepaths{"sessionpath"});
my($session) = Moz::MacCVS->new( $cvsfile );
unless (defined($session)) { die "Error: Checkout aborted. Cannot create session file: $session" }
# activate MacCVS
ActivateApplication('Mcvs');
my($checkout_start_time) = time();
#print "Time now is $checkout_start_time ($checkout_start_time + 0)\n";
my($this_co);
foreach $this_co (@$modules)
{
my($module, $revision, $date) = ($this_co->[0], $this_co->[1], $this_co->[2]);
# assume that things pulled by date wont change
if ($date ne "") {
print "$module is pulled by date, so ignoring in FastUpdate.\n";
next;
}
my($search_type) = "hours";
my($min_date) = "";
my($max_date) = "";
my($url) = "http://bonsai.mozilla.org/cvsquery.cgi?treeid=default&module=${module}&branch=${revision}&branchtype=match&dir=&file=&filetype=match&who=&whotype=match&sortby=Date&hours=${num_hours}&date=${search_type}&mindate=${min_date}&maxdate=${max_date}&cvsroot=%2Fcvsroot";
if ($revision eq "") {
print "Getting list of checkins to $module from Bonsai...\n";
} else {
print "Getting list of checkins to $module on branch $revision from Bonsai...\n";
}
my(@files) = &get_files_from_content(&get_url_contents($url));
if ($#files > 0)
{
my(@cvs_co_list);
my($co_file);
foreach $co_file (@files)
{
print "Updating $co_file\n";
push(@cvs_co_list, $co_file);
}
my($result) = $session->update($revision, \@cvs_co_list);
# result of 1 is success
if (!$result) { die "Error: Fast update failed\n"; }
} else {
print "No files in this module changed\n";
}
}
saveCheckoutTimestamp($checkout_start_time, $timestamp_file);
return 1;
}
#//--------------------------------------------------------------------------------------------------
#// Checkout
#//--------------------------------------------------------------------------------------------------
sub CheckoutModules($$$)
{
my($modules, $pull_date, $timestamp_file) = @_; # list of modules to check out
my($start_time) = TimeStart();
# assertRightDirectory();
my($cvsfile) = AskAndPersistFile($main::filepaths{"sessionpath"});
my($session) = Moz::MacCVS->new( $cvsfile );
unless (defined($session)) { die "Error: Checkout aborted. Cannot create session file: $session" }
my($checkout_start_time) = time();
# activate MacCVS
ActivateApplication('Mcvs');
my($this_co);
foreach $this_co (@$modules)
{
my($module, $revision, $date) = ($this_co->[0], $this_co->[1], $this_co->[2]);
if ($date eq "") {
$date = $pull_date;
}
CheckOutModule($session, $module, $revision, $date);
# print "Checking out $module with ref $revision, date $date\n";
}
saveCheckoutTimestamp($checkout_start_time, $timestamp_file);
TimeEnd($start_time, "Checkout");
}
#//--------------------------------------------------------------------------------------------------
#// ReadCheckoutModulesFile
#//--------------------------------------------------------------------------------------------------
sub ReadCheckoutModulesFile($$)
{
my($modules_file, $co_list) = @_;
my($checkout_file) = getScriptFolder().":".$modules_file;
local(*CHECKOUT_FILE);
open(CHECKOUT_FILE, "< $checkout_file") || die "Error: failed to open checkout list $checkout_file\n";
while (<CHECKOUT_FILE>)
{
my($line) = $_;
chomp($line);
# ignore comments and empty lines
if ($line =~ /^\#/ || $line =~ /^\s*$/) {
next;
}
my(@cvs_co) = ["", "", ""];
my($module, $revision, $date) = (0, 1, 2);
if ($line =~ /\s*([^#,\s]+)\s*\,\s*([^#,\s]+)\s*\,\s*([^#]+)/)
{
@cvs_co[$module] = $1;
@cvs_co[$revision] = $2;
@cvs_co[$date] = $3;
}
elsif ($line =~ /\s*([^#,\s]+)\s*\,\s*([^#,\s]+)\s*(#.+)?/)
{
@cvs_co[$module] = $1;
@cvs_co[$revision] = $2;
}
elsif ($line =~ /\s*([^#,\s]+)\s*\,\s*,\s*([^#,]+)/)
{
@cvs_co[$module] = $1;
@cvs_co[$date] = $2;
}
elsif ($line =~ /\s*([^#,\s]+)/)
{
@cvs_co[$module] = $1;
}
else
{
die "Error: unrecognized line '$line' in $modules_file\n";
}
# strip surrounding space from date
@cvs_co[$date] =~ s/^\s*|\s*$//g;
# print "Going to check out '@cvs_co[$module]', '@cvs_co[$revision]', '@cvs_co[$date]'\n";
push(@$co_list, \@cvs_co);
}
close(CHECKOUT_FILE);
}
#//--------------------------------------------------------------------------------------------------
#// PullFromCVS
#//--------------------------------------------------------------------------------------------------
sub PullFromCVS($$)
{
unless ( $main::build{pull} ) { return; }
my($modules_file, $timestamp_file) = @_;
StartBuildModule("pull");
my(@cvs_co_list);
ReadCheckoutModulesFile($modules_file, \@cvs_co_list);
if ($main::FAST_UPDATE && $main::options{pull_by_date})
{
die "Error: you can't use FAST_UPDATE if you are pulling by date.\n";
}
my($did_fast_update) = $main::FAST_UPDATE && FastUpdate(\@cvs_co_list, $timestamp_file);
if (!$did_fast_update)
{
my($pull_date) = "";
if ($main::options{pull_by_date})
{
# acceptable CVS date formats are (in local time):
# ISO8601 (e.g. "1972-09-24 20:05") and Internet (e.g. "24 Sep 1972 20:05").
# Perl's localtime() string format also seems to work.
$pull_date = localtime().""; # force string interp.
print "Pulling by date $pull_date\n";
}
CheckoutModules(\@cvs_co_list, $pull_date, $timestamp_file);
}
EndBuildModule("pull");
}
#//--------------------------------------------------------------------------------------------------
#// RunBuild
#//--------------------------------------------------------------------------------------------------
sub RunBuild($$$$)
{
my($do_pull, $do_build, $input_files, $build_prefs) = @_;
InitBuildProgress($input_files->{"buildprogress"});
# if we are pulling, we probably want to do a full build, so clear the build progress
if ($do_pull) {
ClearBuildProgress();
}
# read local prefs, and the build progress file, and set flags to say what to build
SetupBuildParams(\%main::build,
\%main::options,
\%main::optiondefines,
\%main::filepaths,
$input_files->{"buildflags"},
$build_prefs);
# If we were told to pull, make sure we do, overriding prefs etc.
if ($do_pull)
{
$main::build{"pull"} = 1;
}
# transfer this flag
$CodeWarriorLib::CLOSE_PROJECTS_FIRST = $main::CLOSE_PROJECTS_FIRST;
# setup the build log
SetupBuildLog($main::filepaths{"buildlogfilepath"}, $main::USE_TIMESTAMPED_LOGS);
StopForErrors();
if ($main::LOG_TO_FILE) {
RedirectOutputToFile($main::filepaths{"scriptlogfilepath"});
}
# run a pre-build check to see that the tools etc are in order
DoPrebuildCheck();
# do the pull
PullFromCVS($input_files->{"checkoutdata"}, $input_files->{"checkouttime"});
unless ($do_build) { return; }
my($build_start) = TimeStart();
# check the build environment
ConfigureBuildSystem();
# here we load and call methods in the build module indirectly.
# we have to use indirection because the build module can be named
# differently for different builds.
chdir(dirname($0)); # change to the script dir
my($build_module) = $input_files->{"buildmodule"};
# load the build module
require $build_module;
{ # scope for no strict 'refs'
no strict 'refs';
my($package_name) = $build_module;
$package_name =~ s/\.pm$//;
chdir($main::MOZ_SRC);
&{$package_name."::BuildDist"}();
chdir($main::MOZ_SRC);
&{$package_name."::BuildProjects"}();
}
# the build finished, so clear the build progress state
ClearBuildProgress();
TimeEnd($build_start, "Build");
print "Build complete\n";
}
1;

View File

@@ -1,425 +0,0 @@
#!perl -w
package Moz::BuildFlags;
require 5.004;
require Exporter;
# Package that attempts to read a file from the Preferences folder,
# and get build settings out of it
use strict;
use Exporter;
use Cwd;
use File::Basename;
use Moz::Moz;
use Moz::Prefs;
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(
SetupBuildParams
InitBuildProgress
WriteBuildProgress
ClearBuildProgress
ReadBuildProgress
);
my(@build_flags);
my(@options_flags);
my(@filepath_flags);
my(%arrays_list) = (
"build_flags", \@build_flags,
"options_flags", \@options_flags,
"filepath_flags", \@filepath_flags
);
my($progress_file) = "¥ÊBuild progress";
#-------------------------------------------------------------------------------
# appendArrayFlag
#
# Set a flag in the array
#-------------------------------------------------------------------------------
sub appendArrayFlag(@)
{
my($array_name) = shift;
my($setting) = shift;
my($value) = shift;
my(@optional_values);
foreach (@_) {
push(@optional_values, $_);
}
my(@this_flag) = [$setting, $value, @optional_values];
my($flags_array) = $arrays_list{$array_name};
if ($flags_array)
{
push(@{$flags_array}, @this_flag) || die "Failed to append\n";
}
else
{
die "Error: unknown build flags array $array_name\n";
}
}
#-------------------------------------------------------------------------------
# readFlagsFile
#
# Read the file of build flags from disk. File path is relative to the
# script directory.
#-------------------------------------------------------------------------------
sub readFlagsFile($)
{
my($flags_file) = @_;
my($file_path) = $0;
$file_path =~ s/[^:]+$/$flags_file/;
print "Reading build flags from '$file_path'\n";
local(*FLAGS_FILE);
open(FLAGS_FILE, "< $file_path") || die "Error: failed to open flags file $file_path\n";
my($cur_array) = "";
while(<FLAGS_FILE>)
{
my($line) = $_;
chomp($line);
# ignore comments and empty lines
if ($line =~ /^\#/ || $line =~ /^\s*$/) {
next;
}
# 1-word line, probably array name
if ($line =~ /^([^#\s]+)\s*$/)
{
$cur_array = $1;
next;
}
elsif ($line =~ /^([^#\s]+)\s+\"(.+)\"(\s+#.+)?$/) # quoted option, possible comment
{
my($flag) = $1;
my($setting) = $2;
appendArrayFlag($cur_array, $flag, $setting);
}
elsif ($line =~ /^([^#\s]+)((\s+[^#\s]+)+)(\s+#.+)?$/) # multiple word line, possible comment
{
my($flag) = $1;
appendArrayFlag($cur_array, $flag, split(' ', $2));
}
else
{
die "Error: unknown build flag at '$line'\n";
}
}
close(FLAGS_FILE);
}
#-------------------------------------------------------------------------------
# flagsArrayToHash
#
# Utility routine to migrate flag from a 2D array to a hash, where
# item[n][0] is the hash entry name, and item[n][1] is the hash entry value.
#-------------------------------------------------------------------------------
sub flagsArrayToHash($$)
{
my($src_array, $dest_hash) = @_;
my($item);
foreach $item (@$src_array)
{
$dest_hash->{$item->[0]} = $item->[1];
}
}
#-----------------------------------------------
# printHash
#
# Utility routine to print a hash
#-----------------------------------------------
sub printHash($)
{
my($hash_ref) = @_;
print "Printing hash:\n";
my($key, $value);
while (($key, $value) = each (%$hash_ref))
{
print " $key $value\n";
}
}
#-----------------------------------------------
# printBuildArray
#
# Utility routine to print a 2D array
#-----------------------------------------------
sub printBuildArray($)
{
my($build_array) = @_;
my($entry);
foreach $entry (@$build_array)
{
print "$entry->[0] = $entry->[1]\n";
}
}
#-------------------------------------------------------------------------------
# SetBuildFlags
#-------------------------------------------------------------------------------
sub SetBuildFlags($)
{
my($build) = @_;
flagsArrayToHash(\@build_flags, $build);
}
#-------------------------------------------------------------------------------
# SetBuildOptions
#-------------------------------------------------------------------------------
sub SetBuildOptions($)
{
my($options) = @_;
flagsArrayToHash(\@options_flags, $options);
}
#-------------------------------------------------------------------------------
# SetFilepathFlags
#-------------------------------------------------------------------------------
sub SetFilepathFlags($)
{
my($filepath) = @_;
flagsArrayToHash(\@filepath_flags, $filepath);
}
#-------------------------------------------------------------------------------
# SetOptionDefines
#-------------------------------------------------------------------------------
sub SetOptionDefines($)
{
my($optiondefines) = @_;
foreach my $entry (@options_flags)
{
if (defined($entry->[2])) {
$optiondefines->{$entry->[0]}{$entry->[2]} = 1;
}
}
}
#-------------------------------------------------------------------------------
# PropagateAllFlags
#-------------------------------------------------------------------------------
sub PropagateAllFlags($)
{
my($build_array) = @_;
# if "all" is set, set all the flags to 1
unless ($build_array->[0][0] eq "all") { die "Error: 'all' must come first in the flags array\n"; }
if ($build_array->[0][1] == 1)
{
my($index);
foreach $index (@$build_array)
{
$index->[1] = 1;
}
}
}
#//--------------------------------------------------------------------------------------------------
#// _getBuildProgressFile
#//--------------------------------------------------------------------------------------------------
sub _getBuildProgressFile()
{
return $progress_file;
}
#//--------------------------------------------------------------------------------------------------
#// setBuildProgressStart
#//
#// This automagically sets $build{"all"} to 0
#//--------------------------------------------------------------------------------------------------
sub setBuildProgressStart($$)
{
my($build_array, $name) = @_;
my($index);
foreach $index (@$build_array)
{
$index->[1] = 0;
if ($index->[0] eq $name) {
last;
}
}
print "Building from module after $name, as specified by build progress\n";
}
#//--------------------------------------------------------------------------------------------------
#// InitBuildProgress
#//--------------------------------------------------------------------------------------------------
sub InitBuildProgress($)
{
my($prog_file) = @_;
if ($prog_file ne "") {
$progress_file = full_path_to($prog_file);
print "Writing build progress to $progress_file\n";
}
}
#//--------------------------------------------------------------------------------------------------
#// WriteBuildProgress
#//--------------------------------------------------------------------------------------------------
sub WriteBuildProgress($)
{
my($module_built) = @_;
my($progress_file) = _getBuildProgressFile();
if ($progress_file ne "")
{
open(PROGRESS_FILE, ">>$progress_file") || die "Failed to open $progress_file\n";
print(PROGRESS_FILE "$module_built\n");
close(PROGRESS_FILE);
}
}
#//--------------------------------------------------------------------------------------------------
#// ClearBuildProgress
#//--------------------------------------------------------------------------------------------------
sub ClearBuildProgress()
{
my($progress_file) = _getBuildProgressFile();
if ($progress_file ne "") {
unlink $progress_file;
}
}
#//--------------------------------------------------------------------------------------------------
#// WipeBuildProgress
#//--------------------------------------------------------------------------------------------------
sub WipeBuildProgress()
{
print "Ignoring build progress\n";
ClearBuildProgress();
$progress_file = "";
}
#//--------------------------------------------------------------------------------------------------
#// ReadBuildProgress
#//--------------------------------------------------------------------------------------------------
sub ReadBuildProgress($)
{
my($build_array) = @_;
my($progress_file) = _getBuildProgressFile();
my($last_module);
if (open(PROGRESS_FILE, "< $progress_file"))
{
print "Getting build progress from $progress_file\n";
while (<PROGRESS_FILE>)
{
my($line) = $_;
chomp($line);
$last_module = $line;
}
close(PROGRESS_FILE);
}
if ($last_module)
{
setBuildProgressStart($build_array, $last_module);
}
}
#-------------------------------------------------------------------------------
# clearOldBuildSettings
#-------------------------------------------------------------------------------
sub clearOldBuildSettings($$$$)
{
my($build, $options, $optiondefines, $filepaths) = @_;
# empty the arrays in case we're being called twice
@build_flags = ();
@options_flags = ();
@filepath_flags = ();
# and empty the hashes
%$build = ();
%$options = ();
%$optiondefines = ();
%$filepaths = ();
}
#-------------------------------------------------------------------------------
# SetupBuildParams
#-------------------------------------------------------------------------------
sub SetupBuildParams($$$$$$)
{
my($build, $options, $optiondefines, $filepaths, $flags_file, $prefs_file) = @_;
# Empty the hashes and arrays, to wipe out any stale data.
# Needed because these structures persist across two build scripts
# called using 'do' from a parent script.
clearOldBuildSettings($build, $options, $optiondefines, $filepaths);
# Read from the flags file, which sets up the various arrays
readFlagsFile($flags_file);
# If 'all' is set in the build array, propagate that to all entries
PropagateAllFlags(\@build_flags);
# read the user pref file, that can change values in the array
ReadMozUserPrefs($prefs_file, \@build_flags, \@options_flags, \@filepath_flags);
# If build progress exists, this clears flags in the array up to a certain point
if ($main::USE_BUILD_PROGRESS) {
ReadBuildProgress(\@build_flags);
} else {
WipeBuildProgress();
}
# printBuildArray(\@build_flags);
# printBuildArray(\@options_flags);
SetBuildFlags($build);
SetBuildOptions($options);
SetOptionDefines($optiondefines);
SetFilepathFlags($filepaths);
# printHash($build);
# printHash($options);
}
1;

View File

@@ -1,786 +0,0 @@
package Moz::BuildUtils;
require 5.004;
require Exporter;
# Package that contains build util functions specific to the Mozilla build
# process.
use strict;
use Exporter;
use Cwd;
use File::Path;
use File::Basename;
use Mac::Events;
use Mac::StandardFile;
use Moz::Moz;
use Moz::BuildFlags;
use Moz::MacCVS;
#use Moz::ProjectXML; #optional; required for static build only
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(
SetupDefaultBuildOptions
SetupBuildRootDir
StartBuildModule
EndBuildModule
GetBinDirectory
BuildOneProjectWithOutput
BuildOneProject
BuildProject
BuildProjectClean
BuildIDLProject
BuildFolderResourceAliases
AskAndPersistFile
DelayFor
TimeStart
TimeEnd
EmptyTree
SetupBuildLog
SetBuildNumber
SetTimeBomb
UpdateConfigHeader
);
#//--------------------------------------------------------------------------------------------------
#// SetupDefaultBuildOptions
#//--------------------------------------------------------------------------------------------------
sub SetupDefaultBuildOptions($$$)
{
my($debug, $bin_dir, $config_header_file_name) = @_;
# Here we set up defaults for the various build flags.
# If you want to override any of these, it's best to do
# so via the relevant preferences file, which lives in
# System Folder:Preferences:Mozilla build prefs:{build prefs file}.
# For the name of the prefs file, see the .pl script that you
# run to start this build. The prefs files are created when
# you run the build, and contain some documentation.
#-------------------------------------------------------------
# configuration variables that globally affect what is built
#-------------------------------------------------------------
$main::DEBUG = $debug;
$main::PROFILE = 0;
$main::RUNTIME = 0; # turn on to just build runtime support and NSPR projects
$main::GC_LEAK_DETECTOR = 0; # turn on to use GC leak detection
$main::MOZILLA_OFFICIAL = 0; # generate build number
$main::LOG_TO_FILE = 0; # write perl output to a file
#-------------------------------------------------------------
# configuration variables that affect the manner of building,
# but possibly affecting the outcome.
#-------------------------------------------------------------
$main::ALIAS_SYM_FILES = $main::DEBUG;
$main::CLOBBER_LIBS = 1; # turn on to clobber existing libs and .xSYM files before
# building each project
# The following two options will delete all dist files (if you have $main::build{dist} turned on),
# but leave the directory structure intact.
$main::CLOBBER_DIST_ALL = 1; # turn on to clobber all aliases/files inside dist (headers/xsym/libs)
$main::CLOBBER_DIST_LIBS = 0; # turn on to clobber only aliases/files for libraries/sym files in dist
$main::CLOBBER_IDL_PROJECTS = 0; # turn on to clobber all IDL projects.
$main::CLOBBER_PROJECTS = 0; # turn on to remove object code from each project before building it
$main::UNIVERSAL_INTERFACES_VERSION = 0x0320;
#-------------------------------------------------------------
# configuration variables that are preferences for the build,
# style and do not affect what is built.
#-------------------------------------------------------------
$main::CLOSE_PROJECTS_FIRST = 0;
# 1 = close then make (for development),
# 0 = make then close (for tinderbox).
$main::USE_TIMESTAMPED_LOGS = 0;
$main::USE_BUILD_PROGRESS = 1; # track build progress for restartable builds
#-------------------------------------------------------------
# END OF CONFIG SWITCHES
#-------------------------------------------------------------
$main::BIN_DIRECTORY = $bin_dir;
$main::DEFINESOPTIONS_FILE = $config_header_file_name;
}
#//--------------------------------------------------------------------------------------------------
#// SetupBuildRootDir
#//--------------------------------------------------------------------------------------------------
sub SetupBuildRootDir($)
{
my($rel_path_to_script) = @_;
my($cur_dir) = cwd();
$cur_dir =~ s/$rel_path_to_script$//;
chdir($cur_dir) || die "Error: failed to set build root directory to '$cur_dir'.\nYou probably need to put 'mozilla' one level down (in a folder).\n";
$main::MOZ_SRC = cwd();
}
#//--------------------------------------------------------------------------------------------------
#// StartBuildModule
#//--------------------------------------------------------------------------------------------------
sub StartBuildModule($)
{
my($module) = @_;
print("---- Start of $module ----\n");
}
#//--------------------------------------------------------------------------------------------------
#// EndBuildModule
#//--------------------------------------------------------------------------------------------------
sub EndBuildModule($)
{
my($module) = @_;
WriteBuildProgress($module);
print("---- End of $module ----\n");
}
#--------------------------------------------------------------------------------------------------
# GetBinDirectory
#--------------------------------------------------------------------------------------------------
sub GetBinDirectory()
{
if ($main::BIN_DIRECTORY eq "") { die "Dist directory not set\n"; }
return $main::BIN_DIRECTORY;
}
#--------------------------------------------------------------------------------------------------
# AskAndPersistFile stores the information about the user pick inside
# the file $session_storage
#--------------------------------------------------------------------------------------------------
sub AskAndPersistFile($)
{
my ($sessionStorage) = @_;
my $cvsfile;
if (( -e $sessionStorage) &&
open( SESSIONFILE, $sessionStorage ))
{
# Read in the path if available
$cvsfile = <SESSIONFILE>;
chomp $cvsfile;
close SESSIONFILE;
if ( ! -e $cvsfile )
{
print STDERR "$cvsfile has disappeared\n";
undef $cvsfile;
}
}
unless (defined ($cvsfile))
{
# make sure that MacPerl is a front process
ActivateApplication('McPL');
MacPerl::Answer("Could not find your MacCVS session file. Please choose one", "OK");
# prompt user for the file name, and store it
my $macFile = StandardGetFile( 0, "McvD");
if ( $macFile->sfGood() )
{
$cvsfile = $macFile->sfFile();
# save the choice if we can
if ( open (SESSIONFILE, ">" . $sessionStorage))
{
printf SESSIONFILE $cvsfile, "\n";
close SESSIONFILE;
}
else
{
print STDERR "Could not open storage file $sessionStorage for saving $cvsfile\n";
}
}
}
return $cvsfile;
}
#--------------------------------------------------------------------------------------------------
# BuildIDLProject
#
#--------------------------------------------------------------------------------------------------
sub BuildIDLProject($$)
{
my ($project_path, $module_name) = @_;
if ($main::CLOBBER_IDL_PROJECTS)
{
my (@suffix_list) = (".mcp", ".xml");
my ($project_name, $project_dir, $suffix) = fileparse($project_path, @suffix_list);
if ($suffix eq "") { die "Error: Project, $project_path must end in .xml or .mcp\n"; }
my($datafolder_path);
if ($suffix eq ".xml")
{
$datafolder_path = $project_dir . "_" . $project_name . " Data:";
}
else {
$datafolder_path = $project_dir . $project_name . " Data:";
}
print STDERR "Deleting IDL data folder: $datafolder_path\n";
EmptyTree($datafolder_path);
}
BuildOneProject($project_path, "headers", 0, 0, 0);
BuildOneProject($project_path, $module_name.".xpt", 1, 0, 1);
}
#--------------------------------------------------------------------------------------------------
# CreateStaticLibTargets
#
#--------------------------------------------------------------------------------------------------
sub CreateXMLStaticLibTargets($)
{
my($xml_path) = @_;
my (@suffix_list) = (".xml");
my ($project_name, $project_dir, $suffix) = fileparse($xml_path, @suffix_list);
if ($suffix eq "") { die "XML munging: $xml_path must end in .xml\n"; }
#sniff the file to see if we need to fix up broken Pro5-exported XML
print "Parsing $xml_path\n";
my $ide_version = Moz::ProjectXML::SniffProjectXMLIDEVersion($xml_path);
if ($ide_version eq "4.0")
{
my $new_file = $project_dir.$project_name."2.xml";
print "Cleaning up Pro 5 xml to $new_file\n";
Moz::ProjectXML::CleanupPro5XML($xml_path, $new_file);
unlink $xml_path;
rename ($new_file, $xml_path);
}
my $doc = Moz::ProjectXML::ParseXMLDocument($xml_path);
my @target_list = Moz::ProjectXML::GetTargetsList($doc);
my $target;
my %target_hash; # for easy lookups below
foreach $target (@target_list) { $target_hash{$target} = 1; }
foreach $target (@target_list)
{
if ($target =~ /(.+).shlb$/) # if this is a shared lib target
{
my $target_base = $1;
my $static_target = $target_base.".o";
# ensure that this does not exist already
if ($target_hash{$static_target}) {
print "Static target $static_target already exists in project. Not making\n";
next;
}
print "Making static target '$static_target' from target '$target'\n";
Moz::ProjectXML::CloneTarget($doc, $target, $static_target);
Moz::ProjectXML::SetAsStaticLibraryTarget($doc, $static_target, $static_target);
}
}
print "Writing XML file to $xml_path\n";
my $temp_path = $project_dir."_".$project_name.".xml";
Moz::ProjectXML::WriteXMLDocument($doc, $temp_path, $ide_version);
Moz::ProjectXML::DisposeXMLDocument($doc);
if (-e $temp_path)
{
unlink $xml_path;
rename ($temp_path, $xml_path);
}
else
{
die "Error: Failed to add new targets to XML project\n";
}
}
#//--------------------------------------------------------------------------------------------------
#// ProcessProjectXML
#//
#// Helper routine to allow for XML pre-processing. This should read in the XML, process it,
#// and replace the original file with the processed version.
#//--------------------------------------------------------------------------------------------------
sub ProcessProjectXML($)
{
my($xml_path) = @_;
# we need to manually load Moz::ProjectXML, becaues not everyone will have the
# required perl modules in their distro.
my($cur_dir) = cwd();
chdir(dirname($0)); # change to the script dir
eval "require Moz::ProjectXML";
if ($@) { die "Error: could not do Project XML munging because you do not have the correct XML modules installed. Error is:\n################\n $@################"; }
chdir($cur_dir);
CreateXMLStaticLibTargets($xml_path);
}
#//--------------------------------------------------------------------------------------------------
#// Build one project, and make the alias. Parameters are project path, target name, shared library
#// name, make shlb alias (boolean), make xSYM alias (boolean), and is component (boolean).
#//--------------------------------------------------------------------------------------------------
sub BuildOneProjectWithOutput($$$$$$)
{
my ($project_path, $target_name, $output_name, $alias_lib, $alias_xSYM, $component) = @_;
unless ($project_path =~ m/^$main::BUILD_ROOT.+/) { return; }
my (@suffix_list) = (".mcp", ".xml");
my ($project_name, $project_dir, $suffix) = fileparse($project_path, @suffix_list);
if ($suffix eq "") { die "Error: Project, $project_path must end in .xml or .mcp\n"; }
my($dist_dir) = GetBinDirectory();
# Put libraries in "Essential Files" folder, Components in "Components" folder
my($output_dir) = $component ? "Components:" : "Essential Files:";
my($output_path) = $dist_dir.$output_dir;
if ($main::options{static_build})
{
if ($output_name =~ /\.o$/ || $output_name =~ /\.[Ll]ib$/)
{
$alias_xSYM = 0;
$alias_lib = 1;
$output_path = $main::DEBUG ? ":mozilla:dist:static_libs_debug:" : ":mozilla:dist:static_libs:";
}
}
# if the flag is on to export projects to XML, export and munge them
if ($main::EXPORT_PROJECTS && !($project_path =~ /IDL\.mcp$/))
{
my $xml_out_path = $project_path;
$xml_out_path =~ s/\.mcp$/\.xml/;
# only do this if project is newer?
if (! -e $xml_out_path)
{
ExportProjectToXML(full_path_to($project_path), full_path_to($xml_out_path));
ProcessProjectXML($xml_out_path);
}
}
# if the flag is set to use XML projects, default to XML if the file
# is present.
if ($main::USE_XML_PROJECTS && !($project_path =~ /IDL\.mcp$/))
{
my $xml_project_path = $project_dir.$project_name.".xml";
if (-e $xml_project_path)
{
$project_path = $xml_project_path;
$suffix = ".xml";
}
}
if ($suffix eq ".xml")
{
my($xml_path) = $project_path;
# Prepend an "_" onto the name of the generated project file so it doesn't conflict
$project_path = $project_dir . "_" . $project_name . ".mcp";
my($project_modtime) = (-e $project_path ? GetFileModDate($project_path) : 0);
my($xml_modtime) = (-e $xml_path ? GetFileModDate($xml_path) : 0);
if ($xml_modtime > $project_modtime)
{
print("Importing $project_path from $project_name.xml.\n");
unlink($project_path);
# Might want to delete the "xxx.mcp Data" dir ???
ImportXMLProject(full_path_to($xml_path), full_path_to($project_path));
}
}
if ($main::CLOBBER_LIBS)
{
unlink "$project_dir$output_name"; # it's OK if these fail
unlink "$project_dir$output_name.xSYM";
}
DoBuildProject($project_path, $target_name, $main::CLOBBER_PROJECTS);
$alias_lib ? MakeAlias("$project_dir$output_name", "$output_path") : 0;
$alias_xSYM ? MakeAlias("$project_dir$output_name.xSYM", "$output_path") : 0;
}
#//--------------------------------------------------------------------------------------------------
#// For compatiblity with existing scripts, BuildOneProject now just calls
#// BuildOneProjectWithOutput, with the output name and target name identical.
#// Note that this routine assumes that the target name and the shared libary name
#// are the same.
#//--------------------------------------------------------------------------------------------------
sub BuildOneProject($$$$$)
{
my ($project_path, $target_name, $alias_lib, $alias_xSYM, $component) = @_;
BuildOneProjectWithOutput($project_path, $target_name, $target_name,
$alias_lib, $alias_xSYM, $component);
}
#//--------------------------------------------------------------------------------------------------
#// For compatiblity with existing scripts, BuildProject now just calls
#// BuildOneProjectWithOutput, with the output name and target name identical.
#// Note that this routine assumes that the target name and the shared libary name
#// are the same. No aliases of the output are made.
#//--------------------------------------------------------------------------------------------------
sub BuildProject($$)
{
my ($project_path, $target_name) = @_;
BuildOneProjectWithOutput($project_path, $target_name, $target_name, 0, 0, 0);
}
#//--------------------------------------------------------------------------------------------------
#// Identical to BuildProject but clobbers the project before building it.
#//--------------------------------------------------------------------------------------------------
sub BuildProjectClean($$)
{
my ($project_path, $target_name) = @_;
my ($save_clobber_flag) = $main::CLOBBER_PROJECTS;
$main::CLOBBER_PROJECTS = 1;
BuildOneProjectWithOutput($project_path, $target_name, $target_name, 0, 0, 0);
$main::CLOBBER_PROJECTS = $save_clobber_flag;
}
#//--------------------------------------------------------------------------------------------------
#// Make resource aliases for one directory
#//--------------------------------------------------------------------------------------------------
sub BuildFolderResourceAliases($$)
{
my($src_dir, $dest_dir) = @_;
# get a list of all the resource files
opendir(SRCDIR, $src_dir) || die("can't open $src_dir");
my(@resource_files) = readdir(SRCDIR);
closedir(SRCDIR);
# make aliases for each one into the dest directory
print("Placing aliases to all files from $src_dir in $dest_dir\n");
for ( @resource_files )
{
next if $_ eq "CVS";
#print(" Doing $_\n");
if (-l $src_dir.$_)
{
print(" $_ is an alias\n");
next;
}
my($file_name) = $src_dir . $_;
MakeAlias($file_name, $dest_dir);
}
}
#//--------------------------------------------------------------------------------------------------
#// DelayFor
#//
#// Delay for the given number of seconds, allowing the script to be cancelled
#//--------------------------------------------------------------------------------------------------
sub DelayFor($)
{
my($delay_secs) = @_;
STDOUT->autoflush(1);
my($end_time) = time() + $delay_secs;
my($last_time) = 0;
my($cur_time) = time();
while ($cur_time < $end_time)
{
$cur_time = time();
if ($cur_time > $last_time)
{
print ".";
$last_time = $cur_time;
}
WaitNextEvent();
}
print "\n";
STDOUT->autoflush(0);
}
#//--------------------------------------------------------------------------------------------------
#// TimeStart
#//--------------------------------------------------------------------------------------------------
sub TimeStart()
{
return time();
}
#//--------------------------------------------------------------------------------------------------
#// TimeEnd
#//--------------------------------------------------------------------------------------------------
sub TimeEnd($$)
{
use integer;
my($start_time, $operation_name) = @_;
my($end_time) = time();
my($tot_sec) = $end_time - $start_time;
my($seconds) = $tot_sec;
my($hours) = $seconds / (60 * 60);
$seconds -= $hours * (60 * 60);
my($minutes) = $seconds / 60;
$seconds -= $minutes * 60;
print "$operation_name took $hours hours $minutes minutes and $seconds seconds\n";
}
#//--------------------------------------------------------------------------------------------------
#// Remove all files from a tree, leaving directories intact (except "CVS").
#//--------------------------------------------------------------------------------------------------
sub EmptyTree($)
{
my ($root) = @_;
#print "EmptyTree($root)\n";
opendir(DIR, $root);
my $sub;
foreach $sub (readdir(DIR))
{
my $fullpathname = $root.$sub; # -f, -d only work on full paths
# Don't call empty tree for the alias of a directory.
# -d returns true for the alias of a directory, false for a broken alias)
if (-d $fullpathname)
{
if (-l $fullpathname) # delete aliases
{
unlink $fullpathname;
next;
}
EmptyTree($fullpathname.":");
if ($sub eq "CVS")
{
#print "rmdir $fullpathname\n";
rmdir $fullpathname;
}
}
else
{
unless (unlink $fullpathname) { die "Failed to delete $fullpathname\n"; }
}
}
closedir(DIR);
}
#//--------------------------------------------------------------------------------------------------
#// Recurse through a directory hierarchy, looking for MANIFEST files.
#// Currently unused.
#//--------------------------------------------------------------------------------------------------
sub ScanForManifestFiles($$$$)
{
my($dir, $theme_root, $theme_name, $dist_dir) = @_;
opendir(DIR, $dir) or die "Cannot open dir $dir\n";
my @files = readdir(DIR);
closedir DIR;
my $file;
foreach $file (@files)
{
my $filepath = $dir.":".$file;
if (-d $filepath)
{
# print "Looking for MANIFEST files in $filepath\n";
ScanForManifestFiles($filepath, $theme_root, $theme_name, $dist_dir);
}
elsif ($file eq "MANIFEST")
{
# print "Doing manifest file $filepath\n";
# Get the dest path from the first line of the file
open(MANIFEST, $filepath) || die "Could not open file $file";
# Read in the path if available
my($dest_line) = <MANIFEST>;
chomp $dest_line;
close MANIFEST;
$dest_line =~ s|^#!dest[\t ]+|| || die "No destination line found in $filepath\n";
my($dest_path) = $dist_dir."chrome:skins:$theme_name:$dest_line";
# print " Destination is $dest_path\n";
InstallResources($filepath, "$dest_path", 0);
}
}
}
#-----------------------------------------------
# SetupBuildLog
#-----------------------------------------------
sub SetupBuildLog($$)
{
my($logfile_path, $timestamped_log) = @_;
my($logdir) = "";
my($logfile) = $logfile_path;
if ($logfile_path =~ /(.+?:)([^:]+)$/) # ? for non-greedy match
{
$logdir = $1;
$logfile = $2;
mkpath($logdir);
}
if ($timestamped_log)
{
#Use time-stamped names so that you don't clobber your previous log file!
my $now = localtime();
while ($now =~ s@:@.@) {} # replace all colons by periods
OpenErrorLog("${logdir}${now}");
}
else
{
OpenErrorLog("${logdir}${logfile}");
}
}
#-----------------------------------------------
# SetBuildNumber
#-----------------------------------------------
sub SetBuildNumber($$)
{
my($build_num_file, $files_to_touch) = @_;
# Make sure we add the config dir to search, to pick up mozBDate.pm
# Need to do this dynamically, because this module can be used before
# mozilla/config has been checked out.
my ($inc_path) = $0; # $0 is the path to the parent script
$inc_path =~ s/:build:mac:build_scripts:.+$/:config/;
push(@INC, $inc_path);
require mozBDate;
mozBDate::UpdateBuildNumber($build_num_file, $main::MOZILLA_OFFICIAL);
my($file);
foreach $file (@$files_to_touch)
{
print "Writing build number to $file from ${file}.in\n";
mozBDate::SubstituteBuildNumber($file, $build_num_file, "${file}.in");
}
}
#-----------------------------------------------
# SetTimeBomb
#-----------------------------------------------
sub SetTimeBomb($$)
{
my ($warn_days, $bomb_days) = @_;
system("perl :mozilla:config:mac-set-timebomb.pl $warn_days $bomb_days");
}
#//--------------------------------------------------------------------------------------------------
#// Regenerate a configuration header file if necessary
#//--------------------------------------------------------------------------------------------------
sub UpdateConfigHeader($)
{
my($config_path) = @_;
my($config, $oldconfig) = ("", "");
my($define, $definevalue, $defines);
my($k, $l,);
foreach $k (keys(%main::options))
{
if ($main::options{$k})
{
foreach $l (keys(%{$main::optiondefines{$k}}))
{
$my::defines{$l} = $main::optiondefines{$k}{$l};
print "Setting up my::defines{$l}\n";
}
}
}
my $config_headerfile = current_directory().$config_path;
if (-e $config_headerfile)
{
open(CONFIG_HEADER, "< $config_headerfile") || die "$config_headerfile: $!\n";
my($line);
while ($line = <CONFIG_HEADER>)
{
if ($line =~ m/#define\s+([^\s]*)\s+([^\s]*)\s*\n/)
{
$define = $1;
$definevalue = $2;
#canonicalize so that whitespace changes are not significant
my $canon_value = "#define " . $define . " " . $definevalue . "\n";
$oldconfig .= $canon_value;
if (exists ($my::defines{$define}) and ($my::defines{$define} == $definevalue))
{
delete $my::defines{$define};
$config .= $canon_value;
}
}
}
close(CONFIG_HEADER);
}
if (%my::defines)
{
foreach $k (keys(%my::defines))
{
$config .= "#define " . $k . " " . $my::defines{$k} . "\n";
}
}
my $file_name = basename($config_headerfile);
if (($config ne $oldconfig) || (!-e $config_headerfile))
{
printf("Writing new configuration header $file_name\n");
open(CONFIG_HEADER, "> $config_headerfile") || die "$config_headerfile: $!\n";
print(CONFIG_HEADER "/* This file is auto-generated based on build options. Do not edit. */\n");
print CONFIG_HEADER ($config);
close(CONFIG_HEADER);
MacPerl::SetFileInfo("CWIE", "TEXT", $config_headerfile);
}
else
{
printf("Configuration header $file_name is up-to-date\n");
}
}
1;

View File

@@ -1,660 +0,0 @@
#!perl
package Moz::CodeWarriorLib;
=pod
=head1 NAME
CodeWarriorLib - supply interface to CodeWarrior
=head1 SYNOPSIS
#!perl
use CodeWarriorLib;
CodeWarriorLib::activate();
$had_errors = CodeWarriorLib::build_project(
$project_path, $target_name, $recent_errors_file, $clean_build
);
=head1 DESCRIPTION
Replaces the AppleScript library I<CodeWarriorLib>.
=over 4
=cut
use strict;
use Cwd;
use File::Basename;
use Mac::Types;
use Mac::Events;
use Mac::AppleEvents;
use Mac::AppleEvents::Simple;
use Mac::Processes;
use Mac::MoreFiles;
use Mac::StandardFile;
use vars qw($VERSION);
$VERSION = '1.02';
my($app) = 'CWIE';
my($scriptDir) = cwd(); # could use $0 for this
my($ide_loc_file) = "";
# 0 == don't switch CWIE to front app in do_event(), 1 == do switch
# note: activate() still switches when called
$Mac::AppleEvents::Simple::SWITCH = 0;
# $Mac::AppleEvents::Simple::WARN = 1;
# supply your own path to the source here
#_test('PowerPudgeIV:mozilla:mozilla:');
# If you want to understand the gobbldeygook that's used to build Apple Events,
# you should start by reading the AEGizmos documentation.
=pod
=item _get_project($full_path)
A private routine returning a reference to the open project with the given name,
or else the empty string (when that project is not open)
full_path is a string identifying the project to be built and is of the form,
e.g., "HD:ProjectFolder:MyProject.mcp". It must be supplied.
=cut
sub _get_project ($) {
my(
$full_path, $candidate_projects
) = @_;
$candidate_projects = _doc_named(basename($full_path, '*'));
if ($candidate_projects) {
my($cps) = _get_dobj($candidate_projects);
my($num) = AECountItems($cps);
if ($num) { # is a list
foreach (1 .. AECountItems($cps)) {
my($cp) = AEGetNthDesc($cps, $_);
if (lc $full_path eq lc _full_path($cp)) {
return($cp);
}
}
} else { # is only one, not a list
if (lc $full_path eq lc _full_path($cps)) {
return($cps);
}
}
}
return;
}
=pod
=item build_project
Build a selected target of a project, saving any errors to a file, if supplied.
full_path is a string identifying the project to be built and is of the form,
e.g., "HD:ProjectFolder:MyProject.mcp". It must be supplied.
If target_name is the empty string, the current target of the selected project
will be built, else, target_name should be a string matching a target name in
the selected project.
If error_path is the empty string, errors will not be saved to a file,
else, error_path should be the full path of a file to save error messages into.
=cut
$CodeWarriorLib::CLOSE_PROJECTS_FIRST = 0; # If true we close then make. If false, make then close.
my $last_project_built = "";
my $last_project_was_closed = 0;
sub build_project ($;$$$) {
my(
$full_path, $target_name, $error_path,
$remove_object, $p, $project_was_closed, $had_errors
) = @_;
_close_errors_window();
if ($CodeWarriorLib::CLOSE_PROJECTS_FIRST && ($last_project_built ne $full_path))
{
# If we're in "close first" mode, we don't close if the current project
# is the same as the previous one.
if ($last_project_was_closed) {
$p = _get_project($last_project_built);
_close($p);
}
$last_project_built = $full_path;
$last_project_was_closed = 0; # now refers to the new project
}
$project_was_closed = 0;
while (1) {
$p = _get_project($full_path);
if (!$p) {
if ($project_was_closed) {
print "### Error - request for project document failed after opening\n";
die "### possibly CW Pro 4 bug: be sure to close your Find window\n";
}
$project_was_closed = 1;
$last_project_was_closed = 1;
_open_file($full_path);
} else {
last;
}
}
$had_errors = 0;
if ($target_name eq '') {
if ($remove_object) {_remove_object($p)}
_build($p);
} else {
if ($remove_object) {_remove_object($p, $target_name)}
_build($p, $target_name);
}
if ($error_path ne '') {
_save_errors_window($error_path);
}
$had_errors = _close_errors_window();
if (!$CodeWarriorLib::CLOSE_PROJECTS_FIRST)
{
if ($project_was_closed) {
$p = _get_project($full_path);
_close($p);
}
}
return($had_errors);
}
=pod
=item appIsRunning()
=cut
sub _appIsRunning($)
{
my ($appSignature) = @_;
my ($psi);
my ($found) = 0;
my ($appPSN);
foreach $psi (values(%Process))
{
if ($psi->processSignature() eq $appSignature)
{
$appPSN = $psi->processNumber();
$found = 1;
last;
}
}
return $found;
}
=pod
=item appIsFrontmost()
=cut
sub _appIsFrontmost($)
{
my ($appSignature) = @_;
my ($psi);
my ($found) = 0;
my ($appPSN);
foreach $psi (values(%Process))
{
if ($psi->processSignature() eq $appSignature)
{
$appPSN = $psi->processNumber();
$found = 1;
last;
}
}
return (GetFrontProcess() == $appPSN);
}
=pod
=item activate()
Launches CodeWarrior and brings it to the front.
Once found, path will be saved in $idepath_file for future reference.
Edit or delete this file to change the location of the IDE. If app is
moved, C<activate()> will prompt for a new location.
First looks for an open CodeWarrior app. Second, tries to open previously
saved location in ':idepath.txt'. Third, tries to find it and allow user
to choose it with Navigation Services (if present). Fourth, uses good old
GUSI routines built-in to MacPerl for a Choose Directory dialog box.
=cut
sub activate ($) {
$ide_loc_file = $_[0]; # save in global
my($filepath, $appath, $psi) = ($ide_loc_file);
foreach $psi (values(%Process)) {
if ($psi->processSignature() eq $app) {
$appath = $psi->processAppSpec();
_save_appath($filepath, $appath);
last;
}
}
if (!$appath || !-x $appath) {
$appath = _read_appath($filepath);
}
if (!$appath || ! -x $appath)
{
# make sure that MacPerl is a front process
#ActivateApplication('McPL');
MacPerl::Answer("Please locate the CodeWarrior application.", "OK");
# prompt user for the file name, and store it
my $macFile = StandardGetFile( 0, "APPL");
if ( $macFile->sfGood() )
{
$appath = $macFile->sfFile();
}
else
{
die "Operation canceled\n";
}
# if (eval {require Mac::Navigation}) {
# my($options, $nav);
# Mac::Navigation->import();
# $options = NavGetDefaultDialogOptions();
# $options->message('Where is CodeWarrior IDE?');
# $options->windowTitle('Find CodeWarrior IDE');
# $nav = NavChooseObject($Application{$app}, $options);
# die "CodeWarrior IDE not found.\n" if (!$nav || !$nav->file(1));
# $appath = $nav->file(1);
# } else {
# local(*D);
# my $cwd = `pwd`;
# $appath = _get_folder(
# 'Where is the CW IDE folder?',
# dirname($Application{$app})
# );
# die "CodeWarrior IDE not found.\n" if !$appath;
# opendir(D, $appath) or die $!;
# chdir($appath);
# foreach my $file (sort readdir (D)) {
# my(@app) = MacPerl::GetFileInfo($file);
# if ($app[0] && $app[1] &&
# $app[1] eq 'APPL' && $app[0] eq $app
# ) {
# $appath .= $file;
# last;
# }
# }
# chomp($cwd);
# chdir($cwd);
# }
_save_appath($filepath, $appath);
}
my($lp) = LaunchParam->new(
launchAppSpec => $appath,
launchControlFlags => launchContinue() + launchNoFileFlags()
);
unless (LaunchApplication($lp)) {
unlink($filepath);
die $^E;
}
# wait for CodeWarrior to show up in the list of processes
while (!_appIsRunning('CWIE'))
{
WaitNextEvent();
}
# wait for CodeWarrior to come to the front
while (!_appIsFrontmost('CWIE'))
{
WaitNextEvent();
}
}
=pod
=item getCodeWarriorPath()
Returns a file path relative to the CodeWarrior folder
=cut
sub getCodeWarriorPath($)
{
my($subfolder)=@_;
my($app_path) = _read_appath($ide_loc_file);
if ($app_path eq "") { die "Error: Failed to get CodeWarrior IDE path\n"; }
my($codewarrior_root) = $app_path;
$codewarrior_root =~ s/[^:]*$//;
return ($codewarrior_root . $subfolder);
}
=pod
=item getCodeWarriorIDEName()
Returns the name of the CodeWarrior application
=cut
sub getCodeWarriorIDEName()
{
my($subfolder)=@_;
my($app_path) = _read_appath($ide_loc_file);
if ($app_path eq "") { die "Error: Failed to get CodeWarrior IDE path\n"; }
my(@codewarrior_path) = split(/:/, $app_path);
return pop(@codewarrior_path);
}
=pod
=item quit()
Quits CodeWarrior.
=cut
sub quit() {
$last_project_built = "";
$last_project_was_closed = 0;
my($evt) = do_event(qw/aevt quit/, $app);
}
sub _build ($;$) {
my($evt);
if ($_[1]) {
my($prm) =
q"'----':obj {form:name, want:type(TRGT), seld:TEXT(@), from:" .
AEPrint($_[0]) . '}';
$evt = do_event(qw/CWIE MAKE/, $app, $prm, $_[1]);
} else {
my($prm) = q"'----':" . AEPrint($_[0]);
$evt = do_event(qw/CWIE MAKE/, $app, $prm);
}
}
sub _remove_object ($;$) {
my($evt);
if ($_[1]) {
my($prm) =
q"'----':obj {form:name, want:type(TRGT), seld:TEXT(@), from:" .
AEPrint($_[0]) . '}';
$evt = do_event(qw/CWIE RMOB/, $app, $prm, $_[1]);
} else {
my($prm) = q"'----':" . AEPrint($_[0]);
$evt = do_event(qw/CWIE RMOB/, $app, $prm);
}
}
sub _open_file ($) {
my($prm) =
q"'----':obj {form:name, want:type(alis), " .
q"seld:TEXT(@), from:'null'()}";
do_event(qw/aevt odoc/, $app, $prm, $_[0]);
}
sub import_project ($$) {
my($xml_file, $project_path) = @_;
my($prm) = "kocl:type(PRJD), rtyp:TEXT(@), data:TEXT(@), &subj:'null'()";
my($evt) = do_event(qw/core crel/, $app, $prm, $project_path, $xml_file);
my($result) = _get_event_result($evt);
if ($result eq "") {
_close(_get_project($project_path));
}
return $result;
}
sub export_project ($$) {
my($project_path, $xml_out_path) = @_;
my($p, $project_was_closed);
$project_was_closed = 0;
while (1) {
$p = _get_project($project_path);
if (!$p) {
if ($project_was_closed) {
print "### Error - request for project document failed after opening\n";
die "### possibly CW bug: be sure to close your Find window\n";
}
$project_was_closed = 1;
_open_file($project_path);
} else {
last;
}
}
# avoid problems with the Project Messages window
_close_named_window("Project Messages");
my($prm) =
q"'----':obj {form:indx, want:type(PRJD), " .
q"seld:1, from:'null'()}, kfil:TEXT(@)";
my($evt) = do_event(qw/CWIE EXPT/, $app, $prm, $xml_out_path);
if ($project_was_closed) {
$p = _get_project($project_path);
_close($p);
}
return _get_event_result($evt);
}
sub _doc_named ($) {
my($prm) =
q"'----':obj {form:test, want:type(docu), from:'null'(), " .
q"seld:cmpd{relo:'= ', 'obj1':obj {form:prop, want:type" .
q"(prop), seld:type(pnam), from:'exmn'()}, 'obj2':TEXT(@)}}";
my($evt) = do_event(qw/core getd/, $app, $prm, $_[0]);
return($evt->{REPLY} eq 'aevt\ansr{}' ? undef : $evt);
}
sub _full_path ($) {
my($obj) = $_[0];
my($prm) =
q"'----':obj {form:prop, want:type(prop), seld:type(FILE), " .
q"from:" . AEPrint($_[0]) . q"}, rtyp:type(TEXT)";
my($evt) = do_event(qw/core getd/, $app, $prm);
return MacPerl::MakePath(
MacUnpack('fss ', (
AEGetParamDesc($evt->{REP}, keyDirectObject()))->data()->get()
)
);
}
sub _save_errors_window ($) {
my($prm) =
q"'----':obj {form:name, want:type(alis), seld:TEXT(@), from:'null'()}";
do_event(qw/MMPR SvMs/, $app, $prm, $_[0]);
}
sub _close_errors_window () {
return _close_named_window('Errors & Warnings');
}
sub _close_named_window ($) {
my($window_name) = @_;
my($prm) =
q"'----':obj {form:name, want:type(cwin), " .
q"seld:TEXT(@), from:'null'()}";
my($evt) = do_event(qw/core clos/, $app, $prm, $window_name);
return($evt->{REPLY} eq 'aevt\ansr{}' ? 1 : 0);
}
sub _close () {
my($prm) = q"'----':" . AEPrint($_[0]);
do_event(qw/core clos/, $app, $prm);
}
sub _get_dobj ($) {
return(AEGetParamDesc($_[0]->{REP}, keyDirectObject()));
}
sub _get_folder ($$) {
require 'GUSI.ph';
my($prompt, $default) = @_;
MacPerl::Choose(
GUSI::AF_FILE(), 0, $prompt, '',
GUSI::CHOOSE_DIR() + ($default ? &GUSI::CHOOSE_DEFAULT : 0),
$default
);
}
sub _get_event_result ($)
{
my($evt) = @_;
my($result) = $evt->{ERROR};
if ( $result eq "" && $evt->{ERRNO} != 0 )
{
$result = "unknown error (".$evt->{ERRNO}.")";
}
return $result;
}
sub _save_appath ($$) {
my($cwd) = cwd(); # remember the current working dir
chdir($scriptDir); # change dir to the script dir
local(*F);
open(F, '>' . $_[0]) or die $!;
print F $_[1];
close(F);
chdir($cwd); # restore the cwd
}
sub _read_appath ($) {
my($filepath) = @_;
my($cwd) = cwd(); # remember the current working dir
chdir($scriptDir); # change dir to the script dir
if (! -e $filepath) {
return "";
}
local(*F);
open(F, $filepath);
my($appath) = <F>;
close(F);
chdir($cwd); # restore the cwd
return($appath);
}
sub _test ($) {
activate($ide_loc_file);
my($path) = $_[0];
build_project(
"${path}modules:xml:macbuild:XML.mcp", '',
"${path}build:mac:Mozilla.BuildLog.part"
);
}
1;
=pod
=back
=head1 HISTORY
=over 4
=item v1.02, September 23, 1998
Made fixes in finding and saving location of CodeWarrior IDE.
=item v1.01, June 1, 1998
Made fixes to C<chdir()> in C<activate()>, made C<activate()> more robust
in finding CodeWarrior IDE, added global variable to NOT switch to IDE
for each sent event, a few other fixes.
=item v1.00, May 30, 1998
First shot
=back
=head1 AUTHORS
Chris Nandor F<E<lt>pudge@pobox.comE<gt>>, and the author of the
original I<CodeWarriorLib>, Scott Collins F<E<lt>scc@netscape.comE<gt>>.
=head1 SEE ALSO
BuildProject L<Moz>.
=head1 COPYRIGHT
The contents of this file are subject to the Netscape Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The Original Code is Mozilla Communicator client code, released
March 31, 1998.
The Initial Developer of the Original Code is Netscape
Communications Corporation. Portions created by Netscape are
Copyright (C) 1998-1999 Netscape Communications Corporation. All
Rights Reserved.
Contributor(s):
=cut

View File

@@ -1,573 +0,0 @@
#!perl -w
package Moz::Jar;
#
# Module for creating jar files, either using a jar manifest, or
# simply jarring up folders on disk.
#
require 5.004;
require Exporter;
use strict;
use Archive::Zip;
use File::Path;
use Mac::Files;
use Moz::Moz;
use vars qw( @ISA @EXPORT );
@ISA = qw(Exporter);
@EXPORT = qw(
CreateJarFileFromDirectory
CreateJarFromManifest
WriteOutJarFiles
SanityCheckJarOptions
);
#-------------------------------------------------------------------------------
# Add the contents of a directory to the zip file
#
#-------------------------------------------------------------------------------
sub _addDirToJar($$$$)
{
my($dir, $jar_root, $zip, $compress) = @_;
opendir(DIR, $dir) or die "Error: Cannot open dir $dir\n";
my @files = readdir(DIR);
closedir DIR;
my $unix_jar_root = $jar_root;
$unix_jar_root =~ s|:|/|g; # colon to slash conversion
my $file;
foreach $file (@files)
{
my $filepath = $dir.":".$file;
if (-d $filepath)
{
print "Adding files to jar from $filepath\n";
_addDirToJar($filepath, $jar_root, $zip, $compress);
}
else
{
my $member = Archive::Zip::Member->newFromFile($filepath);
die "Error: Failed to create zip file member $filepath\n" unless $member;
my $unixName = $filepath;
$unixName =~ s|:|/|g; # colon to slash conversion
$unixName =~ s|^$unix_jar_root||; # relativise
$member->fileName($unixName);
# print "Adding $file as $unixName\n";
if ($compress) {
$member->desiredCompressionMethod(Archive::Zip::COMPRESSION_DEFLATED);
} else {
$member->desiredCompressionMethod(Archive::Zip::COMPRESSION_STORED);
}
$zip->addMember($member);
}
}
}
#-------------------------------------------------------------------------------
# Add the contents of a directory to the zip file
#
#-------------------------------------------------------------------------------
sub CreateJarFileFromDirectory($$$)
{
my($srcdir, $jarpath, $compress) = @_;
my $zip = Archive::Zip->new();
_addDirToJar($srcdir, $srcdir, $zip, $compress);
print "Saving zip file...\n";
my $status = $zip->writeToFileNamed($jarpath);
if ($status == 0) {
print "Zipping completed successfully\n";
} else {
print "Error saving zip file\n";
}
# set the file type/creator to something reasonable
MacPerl::SetFileInfo("ZIP ", "ZIP ", $jarpath);
}
#-------------------------------------------------------------------------------
# printZipContents
#
#-------------------------------------------------------------------------------
sub printZipContents($)
{
my($zip) = @_;
my(@members) = $zip->memberNames();
print "Zip contains:\n";
my($member);
foreach $member (@members)
{
print " $member\n";
}
}
#-------------------------------------------------------------------------------
# safeSaveJarFile
#
# Archive::Zip has a problem where you cannot save a zip file on top of
# an existing zip file that it has open, because it holds references
# into that zip. So we have to save to a temp file, then do a swap.
#
# Note that the zip will become invalid after this operation.
# If you want to do further operations on it, you'll have to reread it.
#-------------------------------------------------------------------------------
sub safeSaveJarFile($$)
{
my($zip, $full_dest_path) = @_;
my($temp_file_name) = $full_dest_path."_temp";
($zip->writeToFileNamed($temp_file_name) == Archive::Zip::AZ_OK) || die "Error: died writing jar to temp file $temp_file_name\n";
unlink $full_dest_path;
(rename $temp_file_name, $full_dest_path) || die "Error: Failed to rename $temp_file_name\n";
MacPerl::SetFileInfo("ZIP ", "ZIP ", $full_dest_path);
}
#-------------------------------------------------------------------------------
# addToJarFile
#
# Add a file to a jar file
#
# Parameters:
# 1. Jar ID. Unix path of jar file inside chrome.
# 2. Abs path to jar.mn file (i.e. source) (mac breaks)
# 3. File source, relative to jar.mn path (mac breaks)
# 4. Abs path to the resulting .jar file (mac breaks)
# 5. Relative file path within the jar (unix breaks)
# 6. Reference to hash of jar files
#
#-------------------------------------------------------------------------------
sub addToJarFile($$$$$$$)
{
my($jar_id, $jar_man_dir, $file_src, $jar_path, $file_jar_path, $override, $jars) = @_;
# print "addToJarFile with:\n $jar_man_dir\n $file_src\n $jar_path\n $file_jar_path\n";
unless ($jar_path =~ m/(.+:)([^:]+)$/) { die "Error: Bad jar path $jar_path\n"; }
my($target_dir) = $1;
my($jar_name) = $2;
$target_dir =~ s/[^:]+$//;
# print "¥ $target_dir $jar_name\n";
# find the source file
my($src) = $jar_man_dir.":".$file_src;
if ((!-e $src) && ($file_src =~ m/.+:([^:]+)$/)) # src does not exist. Fall back to looking for src in jar.mn dir
{
$file_src = $1;
$src = $jar_man_dir.":".$file_src;
if (!-e $src) {
die "Error: Can't find chrome file $src\n";
}
}
if ($main::options{chrome_jars})
{
my($zip) = $jars->{$jar_id};
unless ($zip) { die "Error: Can't find Zip entry for $jar_id\n"; }
# print "Adding $file_src to jar file $jar_path at $file_jar_path\n";
my($member) = Archive::Zip::Member->newFromFile($src);
unless ($member) { die "Error: Failed to create zip file member $src\n"; }
$member->fileName($file_jar_path);
my($compress) = 1;
if ($compress) {
$member->desiredCompressionMethod(Archive::Zip::COMPRESSION_DEFLATED);
$member->desiredCompressionLevel(Archive::Zip::COMPRESSION_LEVEL_DEFAULT); # defaults to 6
} else {
$member->desiredCompressionMethod(Archive::Zip::COMPRESSION_STORED);
}
my($old_member) = $zip->memberNamed($file_jar_path);
if ($override)
{
if ($old_member)
{
# print "Overriding $file_jar_path in jar file $jar_id\n";
# need to compare mod dates or use the + here
$zip->removeMember($old_member);
}
$zip->addMember($member);
}
else
{
if ($old_member)
{
#compare dates here
my($member_moddate) = $old_member->lastModTime();
my($file_moddate) = GetFileModDate($src);
if ($file_moddate > $member_moddate)
{
print "Updating older file $file_jar_path in $jar_id\n";
$zip->removeMember($old_member);
$zip->addMember($member);
}
else
{
print "File $file_jar_path in $jar_id is more recent. Not updating.\n";
}
}
else
{
$zip->addMember($member);
}
}
}
if ($main::options{chrome_files}) # we install raw files too
{
my($rel_path) = $file_jar_path;
$rel_path =~ s|/|:|g; # slash to colons
my($dir_name) = $jar_name;
$dir_name =~ s/\.jar$//;
my($dst) = $target_dir.$dir_name.":".$rel_path;
# print "Aliassing $src\n to\n$dst\n";
if ($override)
{
unlink $dst;
MakeAlias($src, $dst); # don't check errors, otherwise we fail on replacement
}
else
{
if (-e $dst)
{
#compare dates here
my($dst_moddate) = GetFileModDate($dst);
my($file_moddate) = GetFileModDate($src);
if ($file_moddate > $dst_moddate)
{
print "Updating older file $rel_path in $dir_name\n";
unlink $dst;
MakeAlias($src, $dst);
}
else
{
print "File $file_jar_path in $jar_id is more recent. Not updating.\n";
}
}
else
{
MakeAlias($src, $dst);
}
}
}
}
#-------------------------------------------------------------------------------
# setupJarFile
#
# setup a zip for writing
#-------------------------------------------------------------------------------
sub setupJarFile($$$)
{
my($jar_id, $dest_path, $jar_hash) = @_;
# print "Creating jar file $jar_id at $jar_path\n";
my($jar_file) = $jar_id;
$jar_file =~ s|/|:|g; # slash to colons
my($full_jar_path) = full_path_to($dest_path.":".$jar_file);
if ($main::options{chrome_jars})
{
my($zip) = $jar_hash->{$jar_id};
if (!$zip) # if we haven't made it already, do so
{
my($zip) = Archive::Zip->new();
$jar_hash->{$jar_id} = $zip;
# does the jar file exist already? If so, read it in
if (-e $full_jar_path)
{
print "Reading in jar file $jar_id\n";
if ($zip->read($full_jar_path) != Archive::Zip::AZ_OK) { die "Error: Failed to re-read $full_jar_path\n"; }
# printZipContents($zip);
}
}
}
else
{
# installing files.
# nothing to do. MakeAlias creates dirs as needed.
# add this jar to the list
$jar_hash->{$jar_id} = 1;
}
}
#-------------------------------------------------------------------------------
# closeJarFile
#
# We're done with this jar file _for this jar.mn_. We may add more entries
# to it later, so keep it open in the hash.
#-------------------------------------------------------------------------------
sub closeJarFile($$)
{
my($jar_path, $jar_hash) = @_;
# print "Closing jar file $jar_path\n";
if ($main::options{chrome_jars})
{
}
else
{
# installing files.
# nothing to do
}
}
#-------------------------------------------------------------------------------
# WriteOutJarFiles
#
# Now we dump out the jars
#-------------------------------------------------------------------------------
sub WriteOutJarFiles($$)
{
my($chrome_dir, $jars) = @_;
unless ($main::options{chrome_jars}) { return; }
my($full_chrome_path) = full_path_to($chrome_dir);
my($key);
foreach $key (keys %$jars)
{
my($zip) = $jars->{$key};
my($rel_path) = $key;
$rel_path =~ s/\//:/g;
my($output_path) = $full_chrome_path.":".$rel_path;
print "Writing zip file $key to $output_path\n";
# ensure the target dirs exist
my($path) = $output_path;
$path =~ s/[^:]+$//;
mkpath($path);
# unlink $output_path; # remove any existing jar
safeSaveJarFile($zip, $output_path);
# $zip is invalid after this operation, so nuke it here
$jars->{$key} = 0;
}
}
#-------------------------------------------------------------------------------
# registerChromePackage
#
# Enter a chrome package into the installed-chrome.txt file
#-------------------------------------------------------------------------------
sub registerChromePackage($$$$$$)
{
my($jar_file, $file_path, $chrome_dir, $jar_hash, $chrome_type, $pkg_name) = @_;
my($manifest_subdir) = $jar_file;
$manifest_subdir =~ s/:/\//g;
my($chrome_entry);
if ($main::options{use_jars}) {
$chrome_entry = "$chrome_type,install,url,jar:resource:/chrome/$manifest_subdir!/$chrome_type/$pkg_name";
} else {
$manifest_subdir =~ s/\.jar$//;
$chrome_entry = "$chrome_type,install,url,resource:/chrome/$manifest_subdir/$chrome_type/$pkg_name";
}
# print "Entering $chrome_entry in installed-chrome.txt\n";
# ensure chrome_dir exists
mkpath($chrome_dir);
my($inst_chrome) = ${chrome_dir}.":installed-chrome.txt";
if (open(CHROMEFILE, "<$inst_chrome")) {
while (<CHROMEFILE>) {
chomp;
if ($_ eq $chrome_entry) {
# $chrome_entry already appears in installed-chrome.txt file
# just update the mod date
my $now = time;
utime($now, $now, $inst_chrome) || die "Error: Couldn't touch $inst_chrome";
print "+++ updating chrome $inst_chrome\n+++\t\t$chrome_entry\n";
close(CHROMEFILE) || die "Error: can't close $inst_chrome: $!";
return 0;
}
}
close(CHROMEFILE) || die "Error: can't close $inst_chrome: $!";
}
open(CHROMEFILE, ">>${inst_chrome}") || die "Error: Failed to open $inst_chrome\n";
print(CHROMEFILE "${chrome_entry}\n");
close(CHROMEFILE) || die "Error: Failed to close $inst_chrome\n";
print "+++ adding chrome $inst_chrome\n+++\t\t$chrome_entry\n";
}
#-------------------------------------------------------------------------------
# Create or add to a jar file from a jar.mn file.
# Both arguments are relative to the mozilla root dir.
#
#
#-------------------------------------------------------------------------------
sub CreateJarFromManifest($$$)
{
my($jar_man_path, $dest_path, $jars) = @_;
if ($main::options{chrome_jars}) {
print "Jarring from $jar_man_path\n";
}
if ($main::options{chrome_files}) {
print "Installing files from $jar_man_path\n";
}
$jar_man_path = full_path_to($jar_man_path);
$dest_path = full_path_to($dest_path);
# if the jars hash is empty, nuke installed-chrome.txt
if (! scalar(%$jars))
{
print "Nuking installed-chrome.txt\n";
my($installed_chrome) = $dest_path.":installed-chrome.txt";
# unlink $installed_chrome;
}
my $jar_man_dir = "";
my $jar_man_file = "";
if ($jar_man_path =~ /(.+):([^:]+)$/)
{
$jar_man_dir = $1; # no trailing :
$jar_man_file = $2;
}
# Keep a hash of jar files, keyed on relative jar path (e.g. "packages/core.jar")
# Entries are open Archive::Zips (if zipping), and installed-chrome entries.
my($jar_id) = ""; # Current foo/bar.jar from jar.mn file
my($jar_file) = ""; # relative path to jar file (from $dest_path), with mac separators
my($full_jar_path);
open(FILE, "<$jar_man_path") || die "Error: could not open \"$jar_man_path\": $!";
while (<FILE>)
{
my($line) = $_;
chomp($line);
# print "$line\n";
if ($line =~ /^\s*\#.*$/) { # skip comments
next;
}
if ($line =~/^([\w\d.\-\_\\\/]+)\:\s*$/) # line start jar file entries
{
$jar_id = $1;
$jar_file = $jar_id;
$jar_file =~ s|/|:|g; # slash to colons
$full_jar_path = $dest_path.":".$jar_file;
setupJarFile($jar_id, $dest_path, $jars);
}
elsif ($line =~ /^(\+?)\s+([\w\d.\-\_\\\/]+)\s*(\([\w\d.\-\_\\\/]+\))?$\s*/) # jar file entry
{
my($override) = ($1 eq "+");
my($file_dest) = $2;
my($file_src) = $3;
if ($file_src) {
$file_src = substr($file_src, 1, -1); #strip the ()
} else {
$file_src = $file_dest;
}
$file_src =~ s|/|:|g;
if ($jar_file ne "") # if jar is open, add to jar
{
if ($file_dest =~ /([\w\d.\-\_]+)\/([\w\d.\-\_\\\/]+)contents.rdf/)
{
my $chrome_type = $1;
my $pkg_name = $2;
registerChromePackage($jar_file, $file_dest, $dest_path, $jars, $chrome_type, $pkg_name);
}
addToJarFile($jar_id, $jar_man_dir, $file_src, $full_jar_path, $file_dest, $override, $jars);
}
else
{
die "Error: bad jar.mn format at $line\n";
}
}
elsif ($line =~ /^\s*$/ ) # blank line
{
if ($jar_file ne "") #if a jar file is open, close it
{
closeJarFile($full_jar_path, $jars);
$jar_file = "";
$full_jar_path = "";
}
}
}
close(FILE);
if ($jar_file ne "") #if a jar file is open, close it
{
closeJarFile($full_jar_path, $jars);
}
}
1;

View File

@@ -1,228 +0,0 @@
#!perl -w
package Moz::MacCVS;
# package Mac::Apps::MacCVS; this should really be the name of the package
# but due to our directory hierarchy in mozilla, I am not doing it
require 5.004;
require Exporter;
use strict;
use Exporter;
use vars qw($VERSION @ISA @EXPORT);
use Cwd;
use File::Basename;
use Mac::StandardFile;
use Mac::AppleEvents;
use Mac::AppleEvents::Simple;
@ISA = qw(Exporter);
@EXPORT = qw(new describe checkout update);
$VERSION = "1.00";
# If you want to understand the gobbldeygook that's used to build Apple Events,
# you should start by reading the AEGizmos documentation.
# Architecture:
# cvs session object:
# name - session name
# session_file - session file
#
#
my($last_error) = 0;
my($gAppSig) = 'Mcvs'; # MacCVS Pro
#
# utility routines
#
sub _checkForEventError($)
{
my($evt) = @_;
if ($evt->{ERRNO} != 0)
{
print STDERR "Error. Script returned '$evt->{ERROR} (error $evt->{ERRNO})\n";
$last_error = $evt->{ERRNO};
return 0;
}
return 1; # success
}
#
# Session object methods
#
sub new
{
my ( $proto, $session_file) = @_;
my $class = ref($proto) || $proto;
my $self = {};
if ( defined($session_file) && ( -e $session_file) )
{
$self->{"name"} = basename( $session_file );
$self->{"session_file"} = $session_file;
bless $self, $class;
return $self;
}
else
{
print STDERR "MacCVS->new cvs file < $session_file > does not exist\n";
return;
}
}
# makes sure that the session is open
# assertSessionOpen()
# returns 1 on success
sub assertSessionOpen()
{
my ($self) = shift;
$last_error = 0;
my($prm) =
q"'----':obj {form:name, want:type(alis), seld:TEXT(@), from:'null'()}";
my($evt) = do_event(qw/aevt odoc/, $gAppSig, $prm, $self->{session_file});
return _checkForEventError($evt);
}
# prints the cvs object, used mostly for debugging
sub describe
{
my($self) = shift;
$last_error = 0;
print "MacCVS:: name: ", $self->{name}, " session file: ", $self->{session_file}, "\n";
}
# checkout( self, module, revision, date)
# MacCVS checkout command
# returns 1 on success.
sub checkout()
{
my($self, $module, $revision, $date ) = @_;
unless( defined ($module) ) { $module = ""; } # get rid of the pesky undefined warnings
unless( defined ($revision) ) { $revision = ""; }
unless( defined ($date) ) { $date = ""; }
$last_error = 0;
$self->assertSessionOpen() || die "Error: failed to open MacCVS session file at $self->{session_file}\n";
my($revstring) = ($revision ne "") ? $revision : "(none)";
my($datestring) = ($date ne "") ? $date : "(none)";
print "Checking out $module with revision $revstring, date $datestring\n";
my($prm) =
q"'----':obj {form:name, want:type(docu), seld:TEXT(@), from:'null'()}, ".
q"modl:'TEXT'(@), tagr:'TEXT'(@), tagd:'TEXT'(@) ";
my($evt) = do_event(qw/MCvs cout/, $gAppSig, $prm, $self->{name}, $module, $revision, $date);
return _checkForEventError($evt);
}
# update( self, branch tag, list of paths)
# MacCVS udate command
# returns 1 on success.
# NOTE: MacCVS Pro does not correctly support this stuff yet (as of version 2.7d5).
sub update()
{
my($self, $branch, $paths ) = @_;
$last_error = 0;
$self->assertSessionOpen() || die "Error: failed to open MacCVS session file at $self->{session_file}\n";
if ($branch eq "HEAD") {
$branch = "";
}
my($paths_list) = "";
my($path);
foreach $path (@$paths)
{
if ($paths_list ne "") {
$paths_list = $paths_list.", ";
}
$paths_list = $paths_list."Ò".$path."Ó";
}
my($prm) =
q"'----':obj {form:name, want:type(docu), seld:TEXT(@), from:'null'()}, ".
q"tagr:'TEXT'(@), tFls:[";
$prm = $prm.$paths_list."]";
my($evt) = do_event(qw/MCvs updt/, $gAppSig, $prm, $self->{name}, $branch);
return _checkForEventError($evt);
};
sub getLastError()
{
return $last_error;
}
1;
=pod
=head1 NAME
MacCVS - Interface to MacCVS
=head1 SYNOPSIS
use MacCVS;
$session = MacCVS->new( <session_file_path>) || die "cannot create session";
$session->checkout([module] [revision] [date]) || die "Could not check out";
=head1 DESCRIPTION
This is a MacCVS interface for talking to MacCVS Pro client.
MacCVSSession is the class used to manipulate the session
=item new
MacCVS->new( <cvs session file path>);
Creates a new session. Returns undef on failure.
=item checkout( <module> [revision] [date] )
cvs checkout command. Revision and date are optional
returns 0 on failure
=cut
=head1 SEE ALSO
=over
=item MacCVS Home Page
http://www.maccvs.org/
=back
=head1 AUTHORS
Aleks Totic atotic@netscape.com
Simon Fraser sfraser@netscape.com
=cut
__END__

View File

@@ -1,603 +0,0 @@
=head1 NAME
B<Moz> - routines for automating CodeWarrior builds, and some extra-curricular
activities related to building Mozilla
=head1 SYNOPSIS
use Moz;
OpenErrorLog(":::BuildLog");
StopForErrors();
$Moz::QUIET = 1;
InstallFromManifest(":projects:MANIFEST", $dist_dir);
BuildProjectClean(":projects:SomeProject.mcp", "SomeTarget");
MakeAlias(":projects:SomeProject.shlb", $dist_dir);
DontStopForErrors();
BuildProject(":projects:SomeOtherProject.mcp", "SomeTarget");
=head1 DESCRIPTION
B<Moz> comprises the routines needed to slap CodeWarrior around, force it
to build a sequence of projects, report the results, and a few other things.
This module should only contain functions that are generic to any build,
not just the Mozilla build.
=cut
package Moz::Moz;
require Exporter;
use Cwd;
use File::Copy;
use File::Path;
use File::Basename;
use Mac::Types;
use Mac::Events;
use Mac::Processes;
use ExtUtils::Manifest 'maniread';
use Moz::CodeWarriorLib;
@ISA = qw(Exporter);
@EXPORT = qw( LaunchCodeWarrior
GetCodeWarriorRelativePath
current_directory
full_path_to
DoBuildProject
ImportXMLProject
ExportProjectToXML
OpenErrorLog
MakeAlias
GetFileModDate
StopForErrors
DontStopForErrors
InstallFromManifest
InstallResources
RedirectOutputToFile
Delay
ActivateApplication
IsProcessRunning);
@EXPORT_OK = qw(CloseErrorLog QUIET);
sub current_directory()
{
my $current_directory = cwd();
chop($current_directory) if ( $current_directory =~ m/:$/ );
return $current_directory;
}
sub full_path_to($)
{
my ($path) = @_;
if ( $path =~ m/^[^:]+$/ )
{
$path = ":" . $path;
}
if ( $path =~ m/^:/ )
{
$path = current_directory() . $path;
}
return $path;
}
$logging = 0;
$recent_errors_file = "";
$stop_on_1st_error = 1;
$QUIET = 0;
=head2 Logging all the errors and warnings - C<OpenErrorLog($log_file)>, C<CloseErrorLog()>
The warnings and errors generated in the course of building projects can be logged to a file.
Tinderbox uses this facility to show why a remote build failed.
Logging is off by default.
Start logging at any point in your build process with C<OpenErrorLog($log_file)>.
Stop with C<CloseErrorLog()>.
You never need to close the log explicitly, unless you want to just log a couple of projects in the middle of a big list.
C<CloseErrorLog()> is not exported by default.
=cut
sub CloseErrorLog()
{
if ( $logging )
{
close(ERROR_LOG);
$logging = 0;
StopForErrors() if $stop_on_1st_error;
}
}
sub OpenErrorLog($)
{
my ($log_file) = @_;
CloseErrorLog();
if ( $log_file )
{
$log_file = full_path_to($log_file);
open(ERROR_LOG, ">$log_file") || die "Error: Can't open $log_file\n";
MacPerl::SetFileInfo("CWIE", "TEXT", $log_file);
$log_file =~ m/.+:(.+)/;
$recent_errors_file = full_path_to("$1.part");
$logging = 1;
}
}
=head2 Stopping before it's too late - C<StopForErrors()>, C<DontStopForErrors()>
When building a long list of projects, you decide whether to continue building subsequent projects when one fails.
By default, your build script will C<die> after the first project that generates an error while building.
Change this behavior with C<DontStopForErrors()>.
Re-enable it with C<StopForErrors()>.
=cut
sub StopForErrors()
{
$stop_on_1st_error = 1;
# Can't stop for errors unless we notice them.
# Can't notice them unless we are logging.
# If the user didn't explicitly request logging, log to a temporary file.
if ( ! $recent_errors_file )
{
OpenErrorLog("${TMPDIR}BuildResults");
}
}
sub DontStopForErrors()
{
$stop_on_1st_error = 0;
}
sub log_message($)
{
if ( $logging )
{
my ($message) = @_;
print ERROR_LOG $message;
}
}
sub log_message_with_time($)
{
if ( $logging )
{
my ($message) = @_;
my $time_stamp = localtime();
log_message("$message ($time_stamp)\n");
}
}
sub log_recent_errors($)
{
my ($project_name) = @_;
my $found_errors = 0;
if ( $logging )
{
open(RECENT_ERRORS, "<$recent_errors_file");
while( <RECENT_ERRORS> )
{
if ( /^Error/ || /^CouldnÕt find project file/ || /^Link Error/ )
{
# if (!$found_errors)
# print $_;
$found_errors = 1;
}
print ERROR_LOG $_;
}
close(RECENT_ERRORS);
unlink("$recent_errors_file");
}
if ( $stop_on_1st_error && $found_errors )
{
print ERROR_LOG "### Build failed.\n";
die "### Errors encountered building \"$project_name\".\n";
}
}
sub DoBuildProject($$$)
{
my ($project_path, $target_name, $clean_build) = @_;
$project_path = full_path_to($project_path);
# $project_path =~ m/.+:(.+)/;
# my $project_name = $1;
log_message_with_time("### Building \"$project_path\"");
# Check that the given project exists
if (! -e $project_path)
{
print ERROR_LOG "### Build failed.\n";
die "### Can't find project file \"$project_path\".\n";
}
print "Building \"$project_path\[$target_name\]\"\n";
$had_errors = Moz::CodeWarriorLib::build_project(
$project_path, $target_name, $recent_errors_file, $clean_build
);
WaitNextEvent();
# $had_errors =
#MacPerl::DoAppleScript(<<END_OF_APPLESCRIPT);
# tell (load script file "$CodeWarriorLib") to BuildProject("$project_path", "$project_name", "$target_name", "$recent_errors_file", $clean_build)
#END_OF_APPLESCRIPT
# Append any errors to the globally accumulated log file
# if ( $had_errors ) # Removed this test, because we want warnings, too. -- jrm
{
log_recent_errors($project_path);
}
}
sub ImportXMLProject($$)
{
my ($xml_path, $project_path) = @_;
# my ($codewarrior_ide_name) = Moz::CodeWarriorLib::getCodeWarriorIDEName();
# my $ascript = <<EOS;
# tell application "$codewarrior_ide_name"
# make new (project document) as ("$project_path") with data ("$xml_path")
# end tell
#EOS
# print $ascript."\n";
# my($result) = MacPerl::DoAppleScript($ascript);
# unless ($result) { die "Error: ImportXMLProject AppleScript failed $^E $result\n"; }
#
my($import_error) = Moz::CodeWarriorLib::import_project($xml_path, $project_path);
if ($import_error ne "") {
die "Error: ImportXMLProject failed with error $import_error\n";
}
}
sub ExportProjectToXML($$)
{
my ($project_path, $xml_path) = @_;
my (@suffix_list) = (".mcp");
my ($project_name, $project_dir, $suffix) = fileparse($project_path, @suffix_list);
if ($suffix eq "") { die "Project: $project_path doesn't look like a project file.\n"; }
if (-e $xml_path) {
print "$xml_path exists - not exporting $project_path\n";
}
else {
print "Exporting $project_path to $xml_path\n";
my($export_error) = Moz::CodeWarriorLib::export_project($project_path, $xml_path);
if ($export_error ne "") {
die "Error: export_project failed with error '$export_error'\n";
}
if (! -e $xml_path) {
die "Error: XML export to $xml_path failed\n";
}
}
}
=head2 Miscellaneous
C<MakeAlias($old_file, $new_file)> functions like C<symlink()>, except with better argument defaulting and more explicit error messages.
=cut
sub MakeAlias($$)
{
my ($old_file, $new_file) = @_;
# if the directory to hold $new_file doesn't exist, create it
if ( ($new_file =~ m/(.+:)/) && !-d $1 )
{
mkpath($1);
}
# if a leaf name wasn't specified for $new_file, use the leaf from $old_file
if ( ($new_file =~ m/:$/) && ($old_file =~ m/.+:(.+)/) )
{
$new_file .= $1;
}
my $message = "Can't create a Finder alias (at \"$new_file\")\n for \"$old_file\"; because ";
die "Error: $message \"$old_file\" doesn't exist.\n" unless -e $old_file;
die "Error: $message I won't replace an existing (non-alias) file with an alias.\n" if ( -e $new_file && ! -l $new_file );
# now: $old_file exists; $new_file doesn't (or else, is an alias already)
if ( -l $new_file )
{
# ...then see if it already points to $old_file
my $current_target = full_path_to(readlink($new_file));
my $new_target = full_path_to($old_file);
return if ( $current_target eq $new_target );
# if the desired alias already exists and points to the right thing, then we're done
unlink $new_file;
}
symlink($old_file, $new_file) || die "Error: $message symlink returned an unexpected error.\n";
}
=pod
C<InstallFromManifest()>
=cut
sub InstallFromManifest($;$$)
{
my ($manifest_file, $dest_dir, $flat) = @_;
$flat = 0 unless defined($flat); # if $flat, all rel. paths in MANIFEST get aliased to the root of $dest_dir
$dest_dir ||= ":";
$manifest_file =~ m/(.+):/;
my $source_dir = $1;
chop($dest_dir) if $dest_dir =~ m/:$/;
#Mac::Events->import();
WaitNextEvent();
if ($flat)
{
print "Doing manifest on \"$manifest_file\" FLAT\n" unless $QUIET;
}
else
{
print "Doing manifest on \"$manifest_file\"\n" unless $QUIET;
}
my $read = maniread(full_path_to($manifest_file));
foreach $file (keys %$read)
{
next unless $file;
$subdir = ":";
if (!$flat && ($file =~ /:.+:/ ))
{
$subdir = $&;
}
$file = ":$file" unless $file =~ m/^:/;
MakeAlias("$source_dir$file", "$dest_dir$subdir");
}
}
=pod
C<InstallResources()>
=cut
# parameters are path to MANIFEST file, destination dir, true (to make copies) or false (to make aliases)
sub InstallResources($;$;$)
{
my ($manifest_file, $dest_dir, $copy_files) = @_;
$dest_dir ||= ":";
mkpath($dest_dir) if !-d $dest_dir;
$manifest_file =~ m/(.+):/;
my $source_dir = $1;
chop($dest_dir) if $dest_dir =~ m/:$/;
WaitNextEvent();
print "Installing resources from \"$manifest_file\"\n" unless $QUIET;
my $read = maniread(full_path_to($manifest_file));
foreach $file (keys %$read)
{
next unless $file;
if ($copy_files)
{
copy("$source_dir:$file", "$dest_dir:$file");
}
else
{
MakeAlias("$source_dir:$file", "$dest_dir:$file");
}
}
}
#//--------------------------------------------------------------------------------------------------
#// Delay
#//--------------------------------------------------------------------------------------------------
sub Delay($)
{
my ($delay_seconds) = @_;
$now = time;
$exit_time = $now + $delay_seconds;
while ($exit_time > $now) {
$now = time;
}
}
#//--------------------------------------------------------------------------------------------------
#// GetFileModDate
#//--------------------------------------------------------------------------------------------------
sub GetFileModDate($)
{
my($filePath)=@_;
my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
$atime,$mtime,$ctime,$blksize,$blocks) = stat($filePath);
return $mtime;
}
#//--------------------------------------------------------------------------------------------------
#// LaunchCodeWarrior
#//--------------------------------------------------------------------------------------------------
sub LaunchCodeWarrior($)
{
my($idepath_file) = @_; # full path to IDE location file
my($cur_dir) = cwd();
# this both launches and writes the IDE path file
Moz::CodeWarriorLib::activate($idepath_file);
chdir($cur_dir);
}
#//--------------------------------------------------------------------------------------------------
#// GetCodeWarriorRelativePath
#//--------------------------------------------------------------------------------------------------
sub GetCodeWarriorRelativePath($)
{
my($rel_path) = @_;
return Moz::CodeWarriorLib::getCodeWarriorPath($rel_path);
}
#//--------------------------------------------------------------------------------------------------
#// RedirectOutputToFile
#//--------------------------------------------------------------------------------------------------
sub RedirectOutputToFile($)
{
my($log_file) = @_;
# ensure that folders in the path exist
my($logdir) = "";
my($logfile) = $log_file;
if ($log_file =~ /(.+?:)([^:]+)$/) # ? for non-greedy match
{
$logdir = $1;
$logfile = $2;
mkpath($logdir);
}
print "Output is now being redirected to the file '$log_file'\n";
open(STDOUT, "> $log_file") || die "Can't redirect stdout";
open(STDERR, ">&STDOUT") || die "Can't dup stdout";
select(STDERR); $| = 1; # make unbuffered
select(STDOUT); $| = 1; # make unbuffered
MacPerl::SetFileInfo("CWIE", "TEXT", $log_file);
}
#//--------------------------------------------------------------------------------------------------
#// ActivateApplication
#//--------------------------------------------------------------------------------------------------
sub ActivateApplication($)
{
my ($appSignature) = @_;
my ($psi, $found);
my ($appPSN);
$found = 0;
foreach $psi (values(%Process))
{
if ($psi->processSignature() eq $appSignature)
{
$appPSN = $psi->processNumber();
$found = 1;
last;
}
}
if ($found == 0 || SameProcess($appPSN, GetFrontProcess()))
{
return;
}
SetFrontProcess($appPSN);
while (GetFrontProcess() != $appPSN)
{
WaitNextEvent();
}
}
#//--------------------------------------------------------------------------------------------------
#// IsProcessRunning
#//--------------------------------------------------------------------------------------------------
sub IsProcessRunning($)
{
my($processName, $psn, $psi) = @_;
while ( ($psn, $psi) = each(%Process) ) {
if ($psi->processName eq $processName) { return 1; }
}
return 0;
}
1;
=head1 AUTHORS
Scott Collins <scc@netscape.com>, Simon Fraser <sfraser@netscape.com>, Chris Yeh <cyeh@netscape.com>
=head1 SEE ALSO
BuildMozillaDebug.pl (et al), BuildList.pm, CodeWarriorLib (an AppleScript library)
=head1 COPYRIGHT
The contents of this file are subject to the Netscape Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The Original Code is Mozilla Communicator client code, released
March 31, 1998.
The Initial Developer of the Original Code is Netscape
Communications Corporation. Portions created by Netscape are
Copyright (C) 1998-1999 Netscape Communications Corporation. All
Rights Reserved.
Contributor(s):
=cut

View File

@@ -1,272 +0,0 @@
package Moz::Prefs;
require 5.004;
require Exporter;
# Package that attempts to read a file from the Preferences folder,
# and get build settings out of it
use strict;
use Exporter;
use File::Path;
use Mac::Files;
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(ReadMozUserPrefs);
#-------------------------------------------------------------------------------
#
# GetPrefsFolder
#
#-------------------------------------------------------------------------------
sub GetPrefsFolder()
{
my($prefs_folder) = FindFolder(kOnSystemDisk, kPreferencesFolderType, 1);
return $prefs_folder.":Mozilla build prefs";
}
#-------------------------------------------------------------------------------
#
# SetArrayValue
#
#-------------------------------------------------------------------------------
sub SetArrayValue($$$)
{
my($array_ref, $index1, $index2) = @_;
my($index);
foreach $index (@$array_ref)
{
if ($index->[0] eq $index1)
{
$index->[1] = $index2;
return 1;
}
}
return 0;
}
#-------------------------------------------------------------------------------
#
# WriteDefaultPrefsFile
#
#-------------------------------------------------------------------------------
sub WriteDefaultPrefsFile($)
{
my($file_path) = @_;
my($file_contents);
$file_contents = <<'EOS';
% You can use this file to customize the Mozilla build system.
% The following kinds of lines are allowable:
% Comment lines, which start with a '%' in the first column
% Lines which modify the default build settings. For the list of flags,
% see MozBuildFlags.pm. Examples are:
%
% build pull 0 % don't pull
% options mng 1 % turn mng on
%
% Line containing the special 'buildfrom' flag, which specifies
% where to start the build. Example:
%
% buildfrom nglayout % where to start the build
%
% Lines which specify the location of the files used to store paths
% to the CodeWarrior IDE, and the MacCVS Pro session file. Note quoting
% of paths containing whitespace. Examples:
%
% filepath idepath ::codewarrior.txt
% filepath sessionpath ":Some folder:MacCVS session path.txt"
%
% Lines which modify the build settings like %main::DEBUG.
% Any lines which do not match either of the above are assumed
% to set variables on $main::. Examples:
%
% MOZILLA_OFFICIAL 1
%
EOS
$file_contents =~ s/%/#/g;
local(*PREFS_FILE);
open(PREFS_FILE, "> $file_path") || die "Could not write default prefs file\n";
print PREFS_FILE ($file_contents);
close(PREFS_FILE);
MacPerl::SetFileInfo("McPL", "TEXT", $file_path);
}
#-------------------------------------------------------------------------------
#
# HandlePrefSet
#
#-------------------------------------------------------------------------------
sub HandlePrefSet($$$$)
{
my($flags, $name, $value, $desc) = @_;
if (SetArrayValue($flags, $name, $value)) {
print "Prefs set $desc flag '$name' to '$value'\n";
} else {
die "$desc setting '$name' is not a valid option\n";
}
}
#-------------------------------------------------------------------------------
#
# HandleBuildFromPref
#
#-------------------------------------------------------------------------------
sub HandleBuildFromPref($$)
{
my($build_array, $name) = @_;
my($setting) = 0;
my($index);
foreach $index (@$build_array)
{
if ($index->[0] eq $name) {
$setting = 1;
}
$index->[1] = $setting;
}
if ($setting == 1) {
print "Building from $name onwards, as specified by prefs\n";
} else {
printf "Failed to find buildfrom setting '$name'\n";
}
}
#-------------------------------------------------------------------------------
#
# ReadPrefsFile
#
#-------------------------------------------------------------------------------
sub ReadPrefsFile($$$$$)
{
my($file_path, $build_flags, $options_flags, $filepath_flags, $create_if_missing) = @_;
local(*PREFS_FILE);
if (open(PREFS_FILE, "< $file_path"))
{
print "Reading build prefs from '$file_path'\n";
while (<PREFS_FILE>)
{
my($line) = $_;
chomp($line);
if ($line =~ /^\#/ || $line =~ /^\s*$/) { # ignore comments and empty lines
next;
}
if (($line =~ /^\s*([^#\s]+)\s+([^#\s]+)\s+\"(.+)\"(\s+#.+)?/) ||
($line =~ /^\s*([^#\s]+)\s+([^#\s]+)\s+\'(.+)\'(\s+#.+)?/) ||
($line =~ /^\s*([^#\s]+)\s+([^#\s]+)\s+([^#\s]+)(\s+#.+)?/))
{
my($array_name) = $1;
my($option_name) = $2;
my($option_value) = $3;
# print "Read '$array_name' '$option_name' '$option_value'\n";
if ($array_name eq "build")
{
HandlePrefSet($build_flags, $option_name, $option_value, "Build");
}
elsif ($array_name eq "options")
{
HandlePrefSet($options_flags, $option_name, $option_value, "Options");
}
elsif ($array_name eq "filepath" && $option_name && $option_value)
{
HandlePrefSet($filepath_flags, $option_name, $option_value, "Filepath");
}
else
{
print "Unknown pref option at $line\n";
}
}
elsif ($line =~ /^\s*buildfrom\s+([^#\s]+)(\s+#.+)?/)
{
my($build_start) = $1;
HandleBuildFromPref($build_flags, $build_start);
}
elsif ($line =~ /^\s*([^#\s]+)\s+([^#\s]+)(\s+#.+)?/)
{
my($build_var) = $1;
my($var_setting) = $2;
print "Setting \$main::$build_var to $var_setting\n";
eval "\$main::$build_var = \"$var_setting\"";
}
else
{
print "Unrecognized input line at $line\n";
}
}
close(PREFS_FILE);
}
elsif ($create_if_missing)
{
print "No prefs file found at $file_path; using defaults\n";
my($folder_path) = $file_path;
$folder_path =~ s/[^:]+$//;
mkpath($folder_path);
WriteDefaultPrefsFile($file_path);
}
}
#-------------------------------------------------------------------------------
#
# ReadMozUserPrefs
#
#-------------------------------------------------------------------------------
sub ReadMozUserPrefs($$$$)
{
my($prefs_file_name, $build_flags, $options_flags, $filepath_flags) = @_;
if ($prefs_file_name eq "") { return; }
# if local prefs exist, just use those. Othewise, look in the prefs folder
if (-e $prefs_file_name)
{
# read local prefs
ReadPrefsFile($prefs_file_name, $build_flags, $options_flags, $filepath_flags, 0);
}
else
{
# first read prefs folder prefs
my($prefs_path) = GetPrefsFolder();
$prefs_path .= ":$prefs_file_name";
ReadPrefsFile($prefs_path, $build_flags, $options_flags, $filepath_flags, 1);
}
}
1;

View File

@@ -1,932 +0,0 @@
#!/usr/bin/perl
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Simon Fraser <sfraser@netscape.com>
#
package Moz::ProjectXML;
require 5.004;
require Exporter;
use strict;
use Exporter;
use Cwd;
use XML::DOM;
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(
ParseXMLDocument
DisposeXMLDocument
WriteXMLDocument
CleanupPro5XML
GetTargetsList
CloneTarget
SetAsSharedLibraryTarget
SetAsStaticLibraryTarget
AddTarget
RemoveTarget
GetTargetSetting
SetTargetSetting
getChildElementTextContents
);
#--------------------------------------------------------------------------------------------------
# A module for reading, manipulating, and writing XML-format CodeWarrior project files.
#
# Sample usage:
#
# use ProjectXML;
#
# my $doc = ProjectXML::ParseXMLDocument("Test.mcp.xml");
# ProjectXML::CloneTarget($doc, "Test.shlb", "Test.lib");
# ProjectXML::SetAsStaticLibraryTarget($doc, "Test.lib", "TestOutput.lib");
# ProjectXML::WriteXMLDocument($doc, "Test_out.xml");
# ProjectXML::DisposeXMLDocument($doc);
#
#--------------------------------------------------------------------------------------------------
#//--------------------------------------------------------------------------------------------------
#// ParseXMLDocument
#// Note that the caller must call DisposeXMLDocument on the returned doc
#//--------------------------------------------------------------------------------------------------
sub ParseXMLDocument($)
{
my($doc_path) = @_;
my $parser = new XML::DOM::Parser(ErrorContext => 2);
my $doc = $parser->parsefile($doc_path);
return $doc;
}
#//--------------------------------------------------------------------------------------------------
#// DisposeXMLDocument
#// Needed to avoid memory leaks - cleanup circular references for garbage collection
#//--------------------------------------------------------------------------------------------------
sub DisposeXMLDocument($)
{
my($doc) = @_;
$doc->dispose();
}
#//--------------------------------------------------------------------------------------------------
#// WriteXMLDocument
#//--------------------------------------------------------------------------------------------------
sub _pro5_tag_compression($$)
{
return 1; # Pro 5 is broken and can't import XML with <foo/> style tags
}
sub _pro6plus_tag_compression($$)
{
return 0; # Pro 6 can deal with empty XML tags like <foo/>
}
sub WriteXMLDocument($$$)
{
my($doc, $file_path, $ide_version) = @_;
if ($ide_version eq "4.0")
{
XML::DOM::setTagCompression(\&_pro5_tag_compression);
}
else
{
XML::DOM::setTagCompression(\&_pro6plus_tag_compression);
}
$doc->printToFile($file_path);
}
#//--------------------------------------------------------------------------------------------------
#// CleanupPro5XML
#// XML Projects exported by Pro 5 contain garbage data under the MWMerge_MacOS_skipResources
#// setting. This routine cleans this up, saving the result to a new file
#//--------------------------------------------------------------------------------------------------
sub CleanupPro5XML($$)
{
my($xml_path, $out_path) = @_;
local(*XML_FILE);
open(XML_FILE, "< $xml_path") || die "Error: failed to open file $xml_path\n";
local(*CLEANED_FILE);
open(CLEANED_FILE, "> $out_path") || die "Error: failed to open file $out_path for writing\n";
my $in_skip_resources_settings = 0;
while(<XML_FILE>)
{
my($line) = $_;
if ($line =~ /^<\?codewarrior/) # is processing inst line
{
my $test_line = $line;
chomp($test_line);
my $out_line = $test_line;
if ($test_line =~ /^<\?codewarrior\s+exportversion=\"(.+)\"\s+ideversion=\"(.+)\"\s*\?>$/)
{
my $export_version = $1;
my $ide_version = $2;
$ide_version = "4.0_mozilla"; # pseudo IDE version so we know we touched it
$out_line = "<?codewarrior exportversion=\"".$export_version."\" ideversion=\"".$ide_version."\"?>";
}
print CLEANED_FILE "$out_line\n";
next;
}
if ($line =~ /MWMerge_MacOS_skipResources/)
{
$in_skip_resources_settings = 1;
print CLEANED_FILE "$line";
}
elsif($in_skip_resources_settings && $line =~ /<!-- Settings for/)
{
# leaving bad settings lines. Write closing tag
print CLEANED_FILE " <!-- Corrupted setting entries removed by script -->\n";
print CLEANED_FILE " </SETTING>\n\n";
print CLEANED_FILE "$line";
$in_skip_resources_settings = 0;
}
elsif (!$in_skip_resources_settings)
{
print CLEANED_FILE "$line";
}
}
close(XML_FILE);
close(CLEANED_FILE);
}
#--------------------------------------------------------------------------------------------------
# SniffProjectXMLIDEVersion
#
#--------------------------------------------------------------------------------------------------
sub SniffProjectXMLIDEVersion($)
{
my($xml_path) = @_;
my $found_version = "";
local(*XML_FILE);
open(XML_FILE, "< $xml_path") || die "Error: failed to open file $xml_path\n";
while(<XML_FILE>)
{
my($line) = $_;
chomp($line);
if ($line =~ /^<\?codewarrior/) # is processing inst line
{
unless ($line =~ /^<\?codewarrior\s+exportversion=\"(.+)\"\s+ideversion=\"(.+)\"\s*\?>$/)
{
die "Error: Failed to find ideversion in $xml_path in line $line\n";
}
my $export_version = $1;
my $ide_version = $2;
$found_version = $ide_version;
last;
}
}
close(XML_FILE);
return $found_version;
}
#//--------------------------------------------------------------------------------------------------
#// GetTargetsList
#// Returns an array of target names
#//--------------------------------------------------------------------------------------------------
sub GetTargetsList($)
{
my($doc) = @_;
my $nodes = $doc->getElementsByTagName("TARGET");
my $n = $nodes->getLength;
my @target_names;
for (my $i = 0; $i < $n; $i++)
{
my ($node) = $nodes->item($i);
my($target_name) = getChildElementTextContents($node, "NAME");
push(@target_names, $target_name);
}
return @target_names;
}
#//--------------------------------------------------------------------------------------------------
#// CloneTarget
#// Clone the named target, renaming it to 'new_name'
#//--------------------------------------------------------------------------------------------------
sub CloneTarget($$$)
{
my($doc, $target_name, $new_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
# clone here
my $target_clone = $target_node->cloneNode(1); # deep clone
# -- munge target settings --
# set the target name field
setChildElementTextContents($doc, $target_clone, "NAME", $new_name);
# set the targetname pref
setTargetNodeSetting($doc, $target_clone, "Targetname", $new_name);
# -- insert new target subtree --
my $target_list = $target_node->getParentNode();
$target_list->appendChild($target_clone);
# -- now add to targetorder --
my (@target_order_nodes) = getChildOfDocument($doc, "TARGETORDER");
my $target_order = @target_order_nodes[0];
my $new_order = $doc->createElement("ORDEREDTARGET");
my $order_name = $doc->createElement("NAME");
$new_order->appendChild($order_name);
setChildElementTextContents($doc, $new_order, "NAME", $new_name);
$target_order->appendChild($new_order);
}
#//--------------------------------------------------------------------------------------------------
#// SetAsSharedLibraryTarget
#//
#//--------------------------------------------------------------------------------------------------
sub SetAsSharedLibraryTarget($$$)
{
my($doc, $target_name, $output_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_type", "SharedLibrary");
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_filetype", "1936223330"); #'shlb'
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_outfile", $output_name);
}
#//--------------------------------------------------------------------------------------------------
#// AddFileToTarget
#//
#// Add a file to the specified target(s).
#//
#//--------------------------------------------------------------------------------------------------
sub AddFileToTarget($$$)
{
my($doc, $target_list, $file_name) = @_;
# the file must be added in 3 places:
# 1. in <TARGET><FILELIST><FILE> (with linkage flags if necessary)
# 2. in <TARGET><LINKORDER><FILEREF>
# 3. in <GROUPLIST><GROUP><FILEREF>
die "Write me\n";
}
#//--------------------------------------------------------------------------------------------------
#// RemoveFileFromTarget
#//
#// Remove a file from the specified target, removing it from the entire project
#// if no other targets reference it.
#//
#//--------------------------------------------------------------------------------------------------
sub RemoveFileFromTarget($$$)
{
my($doc, $target_node, $file_name) = @_;
# the file must be removed in 3 places:
# 1. in <TARGET><FILELIST><FILE>
# 2. in <TARGET><LINKORDER><FILEREF>
# 3. in <GROUPLIST><GROUP><FILEREF>
# first, remove from <FILELIST>
my $filelist_node = getFirstChildElement($target_node, "FILELIST");
unless ($filelist_node) { die "Error: failed to find FILELIST node\n"; }
my $file_node = getChildNodeByGrandchildContents($doc, $filelist_node, "FILE", "PATH", $file_name);
unless ($file_node) { return; }
$filelist_node->removeChild($file_node);
# next, remove from <LINKORDER>
my $linkorder_node = getFirstChildElement($target_node, "LINKORDER");
unless ($linkorder_node) { die "Error: failed to find LINKORDER node\n"; }
my $fileref_node = getChildNodeByGrandchildContents($doc, $linkorder_node, "FILEREF", "PATH", $file_name);
unless ($fileref_node) { die "Error: link order node for file $file_name not found\n"; }
$linkorder_node->removeChild($fileref_node);
# last, remove from <GROUPLIST>
# <GROUPLIST> is cross-target, so we have to be careful here.
my $grouplist_node = getChildOfDocument($doc, "GROUPLIST");
unless ($grouplist_node) { die "Error: failed to find GROUPLIST node\n"; }
# if the file isn't in any other targets, remove it from the groups
if (!GetFileInUse($doc, $file_name))
{
print "File $file_name is in no other targest. Removing from project\n";
my @group_nodes;
getChildElementsOfType($doc, $grouplist_node, "GROUP", \@group_nodes);
my $group_node;
foreach $group_node (@group_nodes)
{
my @fileref_nodes;
getChildElementsOfType($doc, $group_node, "FILEREF", \@fileref_nodes);
my $fileref_node;
foreach $fileref_node (@fileref_nodes)
{
my $path_name = getChildElementTextContents($fileref_node, "PATH");
if ($path_name eq $file_name)
{
print "Removing $file_name from project group list\n";
$group_node->removeChild($fileref_node);
last;
}
}
# can a file appear in more than one group?
}
}
}
#//--------------------------------------------------------------------------------------------------
#// SetAsStaticLibraryTarget
#//
#//--------------------------------------------------------------------------------------------------
sub SetAsStaticLibraryTarget($$$)
{
my($doc, $target_name, $output_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_type", "Library");
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_filetype", "1061109567"); #'????'
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_outfile", $output_name);
# static targets don't need any library linkage, so we can remove linkage
# with all .shlb and .Lib files.
my(@obsolete_files) = ("NSStdLibStubs", "InterfacesStubs", "InterfaceLib", "InternetConfigLib");
print " Removing libraries etc. from target\n";
# get all files in target
my @target_files = GetTargetFilesList($doc, $target_name);
my $target_file;
foreach $target_file (@target_files)
{
if ($target_file =~ /(\.shlb|\.lib|\.Lib|\.o|\.exp)$/)
{
RemoveFileFromTarget($doc, $target_node, $target_file);
}
}
print " Removing stub libraries from target\n";
# then remove files with known names
my $obs_file;
foreach $obs_file (@obsolete_files)
{
RemoveFileFromTarget($doc, $target_node, $obs_file);
}
}
#//--------------------------------------------------------------------------------------------------
#// AddTarget
#//
#//--------------------------------------------------------------------------------------------------
sub AddTarget($$)
{
my($doc, $target_name) = @_;
die "Write me\n";
}
#//--------------------------------------------------------------------------------------------------
#// RemoveTarget
#//
#//--------------------------------------------------------------------------------------------------
sub RemoveTarget($$)
{
my($doc, $target_name) = @_;
die "Write me\n";
}
#//--------------------------------------------------------------------------------------------------
#// GetTargetSetting
#// Get the value for the specified setting in the specified target
#//--------------------------------------------------------------------------------------------------
sub GetTargetSetting($$$)
{
my($doc, $target_name, $setting_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
return getTargetNodeSetting($target_node, "VALUE");
}
#//--------------------------------------------------------------------------------------------------
#// SetTargetSetting
#// Set the value for the specified setting in the specified target
#//--------------------------------------------------------------------------------------------------
sub SetTargetSetting($$$$)
{
my($doc, $target_name, $setting_name, $new_value) = @_;
my $target_node = getTargetNode($doc, $target_name);
setTargetNodeSetting($doc, $target_node, "VALUE", $new_value);
}
#//--------------------------------------------------------------------------------------------------
#// GetTargetFilesList
#// Return an array of the files in the target (in filelist order)
#//--------------------------------------------------------------------------------------------------
sub GetTargetFilesList($$)
{
my($doc, $target_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
my @files_list;
my $filelist_node = getFirstChildElement($target_node, "FILELIST");
unless ($filelist_node) { die "Error: failed to find FILELIST node\n"; }
my @file_nodes;
getChildElementsOfType($doc, $filelist_node, "FILE", \@file_nodes);
my $node;
foreach $node (@file_nodes)
{
my $file_name = getChildElementTextContents($node, "PATH");
push(@files_list, $file_name);
}
return @files_list;
}
#//--------------------------------------------------------------------------------------------------
#// FileIsInTarget
#//
#//--------------------------------------------------------------------------------------------------
sub FileIsInTarget($$$)
{
my($doc, $file_name, $target_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
unless ($target_node) { die "Error: no target found called $target_name\n"; }
my $file_node = GetTargetFileNode($doc, $target_node, $file_name);
if ($file_node) {
return 1;
}
return 0;
}
#//--------------------------------------------------------------------------------------------------
#// GetFileTargetsList
#// Return an array of the targets that a file is in (expensive)
#//--------------------------------------------------------------------------------------------------
sub GetFileTargetsList($$)
{
my ($doc, $file_name) = @_;
my @target_list;
my @targets = GetTargetsList($doc);
my $target;
foreach $target (@targets)
{
if (FileIsInTarget($doc, $file_name, $target))
{
push(@target_list, $target);
}
}
return @target_list;
}
#//--------------------------------------------------------------------------------------------------
#// GetTargetFileNode
#//
#//--------------------------------------------------------------------------------------------------
sub GetTargetFileNode($$$)
{
my($doc, $target_node, $file_name) = @_;
my $filelist_node = getFirstChildElement($target_node, "FILELIST");
unless ($filelist_node) { die "Error: failed to find FILELIST node\n"; }
my $file_node = getChildNodeByGrandchildContents($doc, $filelist_node, "FILE", "PATH", $file_name);
return $file_node;
}
#//--------------------------------------------------------------------------------------------------
#// GetFileInUse
#// Return true if the file is used by any target
#//--------------------------------------------------------------------------------------------------
sub GetFileInUse($$)
{
my($doc, $file_name) = @_;
my $targetlist_node = getChildOfDocument($doc, "TARGETLIST");
my $target_node = $targetlist_node->getFirstChild();
while ($target_node)
{
if ($target_node->getNodeTypeName eq "ELEMENT_NODE" &&
$target_node->getTagName() eq "TARGET")
{
# if this is a target node
my $file_node = GetTargetFileNode($doc, $target_node, $file_name);
if ($file_node) {
return 1; # found it
}
}
$target_node = $target_node->getNextSibling();
}
# not found
return 0;
}
#//--------------------------------------------------------------------------------------------------
#// getChildOfDocument
#//--------------------------------------------------------------------------------------------------
sub getChildOfDocument($$)
{
my($doc, $child_type) = @_;
return getFirstChildElement($doc->getDocumentElement(), $child_type);
}
#//--------------------------------------------------------------------------------------------------
#// getFirstChildElement
#//--------------------------------------------------------------------------------------------------
sub getFirstChildElement($$)
{
my($node, $element_name) = @_;
my $found_node;
unless ($node) { die "getFirstChildElement called with empty node\n"; }
#look for the first "element_name" child
my $child_node = $node->getFirstChild();
while ($child_node)
{
if ($child_node->getNodeTypeName eq "ELEMENT_NODE" &&
$child_node->getTagName() eq $element_name)
{
$found_node = $child_node;
last;
}
$child_node = $child_node->getNextSibling();
}
return $found_node;
}
#//--------------------------------------------------------------------------------------------------
#// getChildElementsOfType
#//
#// Return an array of refs to child nodes of the given type
#//--------------------------------------------------------------------------------------------------
sub getChildElementsOfType($$$$)
{
my($doc, $node, $child_type, $array_ref) = @_;
my $child_node = $node->getFirstChild();
while ($child_node)
{
if ($child_node->getNodeTypeName eq "ELEMENT_NODE" &&
$child_node->getTagName() eq $child_type)
{
push(@$array_ref, $child_node);
}
$child_node = $child_node->getNextSibling();
}
}
#//--------------------------------------------------------------------------------------------------
#// getChildElementTextContents
#//--------------------------------------------------------------------------------------------------
#
# Given <FOOPY><NERD>Hi!</NERD></FOOPY>, where $node is <FOOPY>,
# returns "Hi!". If > 1 <NERD> node, returns the contents of the first.
#
sub getChildElementTextContents($$)
{
my($node, $tag_name) = @_;
my $first_element = getFirstChildElement($node, $tag_name);
my $text_node = $first_element->getFirstChild();
my $text_contents = "";
# concat adjacent text nodes
while ($text_node)
{
if ($text_node->getNodeTypeName() ne "TEXT_NODE")
{
last;
}
$text_contents = $text_contents.$text_node->getData();
$text_node = $text_node->getNextSibling();
}
return $text_contents;
}
#//--------------------------------------------------------------------------------------------------
#// setChildElementTextContents
#//--------------------------------------------------------------------------------------------------
sub setChildElementTextContents($$$$)
{
my($doc, $node, $tag_name, $contents_text) = @_;
my $first_element = getFirstChildElement($node, $tag_name);
my $new_text_node = $doc->createTextNode($contents_text);
# replace all child elements with a text element
removeAllChildren($first_element);
$first_element->appendChild($new_text_node);
}
#//--------------------------------------------------------------------------------------------------
#// getChildNodeByContents
#//
#// Consider <foo><bar><baz>Foopy</baz></bar><bar><baz>Loopy</baz></bar></foo>
#// This function, when called with getChildNodeByContents($foonode, "bar", "baz", "Loopy")
#// returns the second <bar> node.
#//--------------------------------------------------------------------------------------------------
sub getChildNodeByGrandchildContents($$$$$)
{
my($doc, $node, $child_type, $gc_type, $gc_contents) = @_; # gc = grandchild
my $found_node;
my $child_node = $node->getFirstChild();
while ($child_node)
{
if ($child_node->getNodeTypeName eq "ELEMENT_NODE" &&
$child_node->getTagName() eq $child_type)
{
# check for a child of this node of type
my $child_contents = getChildElementTextContents($child_node, $gc_type);
if ($child_contents eq $gc_contents)
{
$found_node = $child_node;
last;
}
}
$child_node = $child_node->getNextSibling();
}
return $found_node;
}
#//--------------------------------------------------------------------------------------------------
#// getTargetNode
#//--------------------------------------------------------------------------------------------------
sub getTargetNode($$)
{
my($doc, $target_name) = @_;
my $targetlist_node = getChildOfDocument($doc, "TARGETLIST");
return getChildNodeByGrandchildContents($doc, $targetlist_node, "TARGET", "NAME", $target_name);
}
#//--------------------------------------------------------------------------------------------------
#// getTargetNamedSettingNode
#//--------------------------------------------------------------------------------------------------
sub getTargetNamedSettingNode($$)
{
my($target_node, $setting_name) = @_;
my $setting_node;
my $settinglist_node = getFirstChildElement($target_node, "SETTINGLIST");
my $child_node = $settinglist_node->getFirstChild();
while ($child_node)
{
if ($child_node->getNodeTypeName ne "ELEMENT_NODE")
{
$child_node = $child_node->getNextSibling();
next;
}
if ($child_node->getTagName() eq "SETTING")
{
my $set_name = getChildElementTextContents($child_node, "NAME");
if ($set_name eq $setting_name)
{
$setting_node = $child_node;
last;
}
}
$child_node = $child_node->getNextSibling();
}
return $setting_node;
}
#//--------------------------------------------------------------------------------------------------
#// getTargetNodeSetting
#//--------------------------------------------------------------------------------------------------
sub getTargetNodeSetting($$)
{
my($target_node, $setting_name) = @_;
my $setting_node = getTargetNamedSettingNode($target_node, $setting_name);
return getChildElementTextContents($setting_node, "VALUE");
}
#//--------------------------------------------------------------------------------------------------
#// setTargetNodeSetting
#//--------------------------------------------------------------------------------------------------
sub setTargetNodeSetting($$$$)
{
my($doc, $target_node, $setting_name, $new_value) = @_;
my $setting_node = getTargetNamedSettingNode($target_node, $setting_name);
setChildElementTextContents($doc, $setting_node, "VALUE", $new_value);
}
#//--------------------------------------------------------------------------------------------------
#// elementInArray
#//--------------------------------------------------------------------------------------------------
sub elementInArray($$)
{
my($element, $array) = @_;
my $test;
foreach $test (@$array)
{
if ($test eq $element) {
return 1;
}
}
return 0;
}
#//--------------------------------------------------------------------------------------------------
#// removeAllChildren
#//--------------------------------------------------------------------------------------------------
sub removeAllChildren($)
{
my($node) = @_;
my $child_node = $node->getFirstChild();
while ($child_node)
{
$node->removeChild($child_node);
$child_node = $node->getFirstChild();
}
}
#//--------------------------------------------------------------------------------------------------
#// dumpNodeData
#//--------------------------------------------------------------------------------------------------
sub dumpNodeData($)
{
my($node) = @_;
unless ($node) { die "Null node passed to dumpNodeData\n"; }
print "Dumping node $node\n";
my($node_type) = $node->getNodeTypeName();
if ($node_type eq "ELEMENT_NODE")
{
my($node_name) = $node->getTagName();
print "Element $node_name\n";
}
elsif ($node_type eq "TEXT_NODE")
{
my($node_data) = $node->getData;
# my(@node_vals) = unpack("C*", $node_data);
print "Text '$node_data'\n"; # may contain LF chars
}
else
{
print "Node $node_type\n";
}
}
#//--------------------------------------------------------------------------------------------------
#// dumpNodeTree
#//--------------------------------------------------------------------------------------------------
sub dumpNodeTree($)
{
my($node) = @_;
my($child_node) = $node->getFirstChild();
unless ($child_node) { return; }
# recurse
dumpNodeData($child_node);
# then go through child nodes
while ($child_node)
{
dumpNodeTree($child_node);
$child_node = $child_node->getNextSibling();
}
}
1;

View File

@@ -1,90 +0,0 @@
#-------------------------------------------------------------------------------
# These 3 lists are the 'master lists' to control what gets built.
#
# Ordering in these arrays is important; it has to reflect the order in
# which the build occurs.
#
# Setting containing spaces must be quoted with double quotes.
#-------------------------------------------------------------------------------
build_flags
all 1
pull 0
dist 0
config 0
xpidl 0
idl 0
stubs 0
runtime 0
common 0
imglib 0
libimg2 0
necko 0
security 0
browserutils 0
intl 0
nglayout 0
accessiblity 0
editor 0
embedding 0
viewer 0
xpapp 0
extensions 0
plugins 0
mailnews 0
apprunner 0
resources 0
options_flags
pull_by_date 0
chrome_jars 1
chrome_files 0
use_jars 1
transformiix 1
mathml 0 MOZ_MATHML
svg 0 MOZ_SVG
# svg requires libart, which is an lgpl library. You need to pull it
# explicitly.
libart_lgpl 0
mng 1
ldap 1 MOZ_LDAP_XPCOM
ldap_experimental 0 MOZ_LDAP_XPCOM_EXPERIMENTAL
xmlextras 1
wsp 0 MOZ_WSP
inspector 1
mailextras 1
xptlink 0
psm 0 MOZ_PSM
embedding_test 1
embedding_chrome 0
embedding_xulprefs 0
embedding_xulsecurity 0
carbon 0 TARGET_CARBON
useimg2 1 USE_IMG2
lowmem 0 MOZ_MAC_LOWMEM
accessible 1 ACCESSIBILITY
bidi 1 IBMBIDI
p3p 0
jsd 1
venkman 1
moz_logging 1 MOZ_LOGGING
chatzilla 1
content_packs 1
xml_rpc 1
cview 1
help 1
timeline 0 MOZ_TIMELINE
static_build 0 MOZ_STATIC_COMPONENT_LIBS
string_debug 0 DEBUG_STRING
string_stats 0 DEBUG_STRING_STATS
xpctools 0 XPC_TOOLS_SUPPORT
smime 1
mdn 1
print_preview 1 NS_PRINT_PREVIEW
moz_xul 1 MOZ_XUL
filepath_flags
idepath ":CodeWarrior IDE Path.txt"
sessionpath ":Mozilla session path.txt"
buildlogfilepath ":Build Logs:Mozilla build log.txt" # this is a path
scriptlogfilepath ":Build Logs:Mozilla script log.txt"

File diff suppressed because it is too large Load Diff

View File

@@ -1,22 +0,0 @@
# List of modules to check out. Format is
# module, (tag), (date)
# where tag and date are optional (non-trailing commas are required)
#
# Examples:
# mozilla/nsprpub, NSPRPUB_CLIENT_TAG
# mozilla/gc, , 10/25/2000 12:00:00
#
mozilla/nsprpub, NETSCAPE_7_0_RTM
mozilla/security/nss, NETSCAPE_7_0_RTM
mozilla/security/manager, NETSCAPE_7_0_RTM
mozilla/accessible, NETSCAPE_7_0_RTM
mozilla/directory/c-sdk, NETSCAPE_7_0_RTM
mozilla/lib/mac/Instrumentation, NETSCAPE_7_0_RTM
mozilla/gfx2, NETSCAPE_7_0_RTM
mozilla/modules/libpr0n, NETSCAPE_7_0_RTM
SeaMonkeyAll, NETSCAPE_7_0_RTM
## You need this if you want to be able to use SVG
## Note that this library is under the LGPL, not the MPL
#mozilla/other-licenses/libart_lgpl

View File

@@ -1,79 +0,0 @@
#!perl
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Simon Fraser <sfraser@netscape.com>
#
require 5.004;
use strict;
use Cwd;
use Moz::BuildUtils;
use Moz::BuildCore;
#-------------------------------------------------------------
# Where have the build options gone?
#
# The various build flags have been centralized into one place.
# The master list of options is in MozBuildFlags.txt. However,
# you should never need to edit that file, or this one.
#
# To customize what gets built, or where to start the build,
# edit the $prefs_file_name file in
# System Folder:Preferences:Mozilla build prefs:
# Documentation is provided in that file.
#-------------------------------------------------------------
my($prefs_file_name) = "Mozilla pull prefs";
#-------------------------------------------------------------
# hashes to hold build options
#-------------------------------------------------------------
my(%build);
my(%options);
my(%filepaths);
my(%optiondefines);
# Hash of input files for this build. Eventually, there will be
# input files for manifests, and projects too.
my(%inputfiles) = (
"buildflags", "MozillaBuildFlags.txt",
"checkoutdata", "MozillaCheckoutList.txt",
"buildprogress", "",
"buildmodule", "MozillaBuildList.pm",
"checkouttime", "Mozilla last checkout"
);
#-------------------------------------------------------------
# end build hashes
#-------------------------------------------------------------
# set the build root directory, which is the the dir above mozilla
SetupBuildRootDir(":mozilla:build:mac:build_scripts");
# Set up all the flags on $main::, like DEBUG, CARBON etc.
# Override the defaults using the preferences files.
SetupDefaultBuildOptions(0, ":mozilla:dist:viewer:", "");
my($do_checkout) = 1;
my($do_build) = 0;
RunBuild($do_checkout, $do_build, \%inputfiles, $prefs_file_name);

View File

@@ -1,511 +0,0 @@
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
DEPTH=.
!if !defined(MOZ_TOP)
#enable builds from changed top level directories
MOZ_TOP=mozilla
!endif
MOZ_SRC_FLIPPED = $(MOZ_SRC:\=/)
MOZ_DIST_FLIPPED = $(MOZ_SRC_FLIPPED)/mozilla/dist
!ifdef MOZ_DEBUG
MOZ_OBJDIR = WIN32_D.OBJ
!else
MOZ_OBJDIR = WIN32_O.OBJ
!endif
#
# Command macro defines
#
#//------------------------------------------------------------------------
#// Figure out how to do the pull.
#//------------------------------------------------------------------------
# uncomment these, modify branch tag, and check in to branch for milestones
MOZ_BRANCH=NETSCAPE_7_0_RTM
NSPR_CO_TAG=NETSCAPE_7_0_RTM
PSM_CO_TAG=NETSCAPE_7_0_RTM
NSS_CO_TAG=NETSCAPE_7_0_RTM
LDAPCSDK_CO_TAG=NETSCAPE_7_0_RTM
ACCESSIBLE_CO_TAG=NETSCAPE_7_0_RTM
IMGLIB2_CO_TAG=NETSCAPE_7_0_RTM
GFX2_CO_TAG=NETSCAPE_7_0_RTM
!ifdef MOZ_BRANCH
CVS_BRANCH=-r $(MOZ_BRANCH)
!endif
!ifdef MOZ_DATE
CVS_BRANCH=$(CVS_BRANCH) -D "$(MOZ_DATE)"
!endif
# default pull is "quiet" but it can be overridden with MOZ_CVS_VERBOSE
!ifndef MOZ_CVS_VERBOSE
CVS_FLAGS=-q
!endif
# honor any user-defined CVS flags
!ifdef MOZ_CVS_FLAGS
CVS_FLAGS=$(CVS_FLAGS) $(MOZ_CVS_FLAGS)
!endif
# let's be explicit about CVSROOT... some windows cvs clients
# are too stupid to correctly work without the -d option
#
# if they are too stupid, they should fail. I am
# commenting this out because this does not work
# under 4nt. (%'s are evaluted differently)
#
# If it breaks you, mail dougt@netscape.com
# and leaf@mozilla.org
#
!if 0
!if defined(CVSROOT)
CVS_FLAGS=$(CVS_FLAGS) -d "$(CVSROOT)"
!endif
!endif
!ifndef MOZ_CO_FLAGS
MOZ_CO_FLAGS = -P
!endif
CVSCO = cvs $(CVS_FLAGS) co $(MOZ_CO_FLAGS) $(CVS_BRANCH)
#//------------------------------------------------------------------------
#// Figure out how to pull NSPR.
#// If no NSPR_CO_TAG is specified, use the default static tag
#//------------------------------------------------------------------------
!ifndef NSPR_CO_FLAGS
NSPR_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
NSPR_CO_FLAGS=$(NSPR_CO_FLAGS) $(CVS_BRANCH)
CVSCO_NSPR = cvs $(CVS_FLAGS) co $(NSPR_CO_FLAGS)
#//------------------------------------------------------------------------
#// Figure out how to pull NSS and PSM libs.
#// If no NSS_CO_TAG or PSM_CO_TAG is specified, use the default static tag
#//------------------------------------------------------------------------
!ifndef NSS_CO_FLAGS
NSS_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
NSS_CO_FLAGS=$(NSS_CO_FLAGS) $(CVS_BRANCH)
CVSCO_NSS = cvs $(CVS_FLAGS) co $(NSS_CO_FLAGS)
!ifndef PSM_CO_FLAGS
PSM_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
PSM_CO_FLAGS=$(PSM_CO_FLAGS) $(CVS_BRANCH)
CVSCO_PSM = cvs $(CVS_FLAGS) co $(PSM_CO_FLAGS)
#//------------------------------------------------------------------------
#// Figure out how to pull LDAP C SDK client libs.
#// If no LDAPCSDK_CO_TAG is specified, use the default tag
#//------------------------------------------------------------------------
!ifndef LDAPCSDK_CO_FLAGS
LDAPCSDK_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
LDAPCSDK_CO_FLAGS=$(LDAPCSDK_CO_FLAGS) $(CVS_BRANCH)
CVSCO_LDAPCSDK = cvs $(CVS_FLAGS) co $(LDAPCSDK_CO_FLAGS)
#//------------------------------------------------------------------------
#// Figure out how to pull accessibility libs.
#// If no ACCESSIBLE_CO_TAG is specified, use the default tag
#//------------------------------------------------------------------------
!ifndef ACCESSIBLE_CO_FLAGS
ACCESSIBLE_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
ACCESSIBLE_CO_FLAGS=$(ACCESSIBLE_CO_FLAGS) $(CVS_BRANCH)
CVSCO_ACCESSIBLE = cvs $(CVS_FLAGS) co $(ACCESSIBLE_CO_FLAGS)
#//------------------------------------------------------------------------
#// Figure out how to pull new image library.
#// If no IMGLIB2_CO_TAG is specified, use the default tag
#//------------------------------------------------------------------------
!ifndef IMGLIB2_CO_FLAGS
IMGLIB2_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
IMGLIB2_CO_FLAGS=$(IMGLIB2_CO_FLAGS) $(CVS_BRANCH)
CVSCO_IMGLIB2 = cvs $(CVS_FLAGS) co $(IMGLIB2_CO_FLAGS)
#//------------------------------------------------------------------------
#// Figure out how to pull new image library.
#// If no GFX2_CO_TAG is specified, use the default tag
#//------------------------------------------------------------------------
!ifndef GFX2_CO_FLAGS
GFX2_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
GFX2_CO_FLAGS=$(GFX2_CO_FLAGS) $(CVS_BRANCH)
CVSCO_GFX2 = cvs $(CVS_FLAGS) co $(GFX2_CO_FLAGS)
#//------------------------------------------------------------------------
#// Figure out how to pull the internal libart
#// (only pulled and built if MOZ_INTERNAL_LIBART_LGPL is set)
#// If no MOZ_INTERNAL_LIBART_CO_TAG is specified, use the default tag
#//------------------------------------------------------------------------
!if defined(MOZ_SVG) && !defined(MOZ_INTERNAL_LIBART_LGPL)
ERR_MESSAGE = ^
You are trying to build Mozilla with SVG support (MOZ_SVG=1), but you ^
haven not specified that mozilla/other-licenses/libart_lgpl should be ^
pulled and built. At the moment Mozilla SVG builds need this patched ^
version of libart. You either need to disable SVG support (unset MOZ_SVG) ^
or enable pulling and building by setting MOZ_INTERNAL_LIBART_LGPL=1.^
^
If you choose to pull and build libart, note that it is only licensed^
under the terms of the LGPL, not the MPL. (Which is why you have to opt^
in explicitly.)
!endif
!if defined(MOZ_INTERNAL_LIBART_LGPL)
!ifndef MOZ_INTERNAL_LIBART_CO_FLAGS
MOZ_INTERNAL_LIBART_CO_FLAGS=$(MOZ_CO_FLAGS)
!endif
!if "$(MOZ_INTERNAL_LIBART_CO_TAG)" != ""
MOZ_INTERNAL_LIBART_CO_FLAGS=$(MOZ_INTERNAL_LIBART_CO_FLAGS) -r $(MOZ_INTERNAL_LIBART_CO_TAG)
!else
MOZ_INTERNAL_LIBART_CO_FLAGS=$(MOZ_INTERNAL_LIBART_CO_FLAGS) $(CVS_BRANCH)
!endif
CVSCO_MOZ_INTERNAL_LIBART = cvs $(CVS_FLAGS) co $(MOZ_INTERNAL_LIBART_CO_FLAGS)
!endif
## The master target
############################################################
pull_and_build_all: pull_all build_all_dep
## Rules for pulling the source from the cvs repository
############################################################
pull_clobber_and_build_all: pull_all clobber_all build_all
!if !defined(MOZ_INTERNAL_LIBART_LGPL)
pull_all: pull_nspr pull_psm pull_ldapcsdk pull_accessible pull_gfx2 pull_imglib2 pull_seamonkey
!else
pull_all: pull_nspr pull_psm pull_ldapcsdk pull_accessible pull_gfx2 pull_imglib2 pull_moz_internal_libart pull_seamonkey
!endif
pull_nspr: pull_clientmak
cd $(MOZ_SRC)\.
$(CVSCO_NSPR) mozilla/nsprpub
pull_nss:
cd $(MOZ_SRC)\.
$(CVSCO_NSS) mozilla/security/coreconf
$(CVSCO_NSS) mozilla/security/nss
pull_psm: pull_nss
cd $(MOZ_SRC)\.
$(CVSCO_PSM) mozilla/security/manager
$(CVSCO_PSM) mozilla/security/makefile.win
pull_ldapcsdk:
cd $(MOZ_SRC)\.
$(CVSCO_LDAPCSDK) mozilla/directory/c-sdk
pull_accessible:
cd $(MOZ_SRC)\.
$(CVSCO_ACCESSIBLE) mozilla/accessible
pull_gfx2:
cd $(MOZ_SRC)\.
$(CVSCO_GFX2) mozilla/gfx2
pull_imglib2:
cd $(MOZ_SRC)\.
$(CVSCO_IMGLIB2) mozilla/modules/libpr0n
!if defined(MOZ_INTERNAL_LIBART_LGPL)
pull_moz_internal_libart:
cd $(MOZ_SRC)\.
$(CVSCO_MOZ_INTERNAL_LIBART) mozilla/other-licenses/libart_lgpl
!endif
pull_xpconnect: pull_nspr
cd $(MOZ_SRC)\.
$(CVSCO) mozilla/include
$(CVSCO) mozilla/config
$(CVSCO) -l mozilla/js
$(CVSCO) -l mozilla/js/src
$(CVSCO) mozilla/js/src/fdlibm
$(CVSCO) mozilla/js/src/xpconnect
$(CVSCO) mozilla/modules/libreg
$(CVSCO) mozilla/xpcom
$(CVSCO) mozilla/string
# pull either layout only or seamonkey the browser
pull_layout:
cd $(MOZ_SRC)\.
$(CVSCO) RaptorWin
pull_seamonkey: pull_clientmak
cd $(MOZ_SRC)\.
$(CVSCO) SeaMonkeyAll
pull_clientmak:
cd $(MOZ_SRC)\.
$(CVSCO) mozilla/client.mak
############################################################
# nmake has to be hardcoded, or we have to depend on mozilla/config
# being pulled already to figure out what $(NMAKE) should be.
clobber_all: clobber_nspr clobber_ldapcsdk clobber_psm clobber_seamonkey
build_all: build_nspr build_ldapcsdk build_seamonkey
build_all_dep: depend libs
distclean:
@cd $(MOZ_SRC)\$(MOZ_TOP)\directory\c-sdk
gmake -f gmakefile.win distclean MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED)
@cd $(MOZ_SRC)\$(MOZ_TOP)\nsprpub
gmake -f gmakefile.win distclean MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED)
@cd $(MOZ_SRC)\$(MOZ_TOP)
nmake /f client.mak clobber_psm
nmake /f client.mak clobber_seamonkey
clobber_ldapcsdk:
@cd $(MOZ_SRC)\$(MOZ_TOP)\directory\c-sdk
gmake -f gmakefile.win clobber_all MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED) \
SHELL=sh
clobber_nspr:
@cd $(MOZ_SRC)\$(MOZ_TOP)\nsprpub
gmake -f gmakefile.win clobber_all MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED)
clobber_psm:
@cd $(MOZ_SRC)\$(MOZ_TOP)\security
nmake -f makefile.win clobber_all
clobber_xpconnect:
@cd $(MOZ_SRC)\$(MOZ_TOP)\.
-rd /s /q dist
@cd $(MOZ_SRC)\$(MOZ_TOP)\nsprpub
gmake -f gmakefile.win clobber_all MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED)
@cd $(MOZ_SRC)\$(MOZ_TOP)\include
nmake -f makefile.win clobber_all
@cd $(MOZ_SRC)\$(MOZ_TOP)\modules\libreg
nmake -f makefile.win clobber_all
@cd $(MOZ_SRC)\$(MOZ_TOP)\string
nmake -f makefile.win clobber_all
@cd $(MOZ_SRC)\$(MOZ_TOP)\xpcom
nmake -f makefile.win clobber_all
@cd $(MOZ_SRC)\$(MOZ_TOP)\js
nmake -f makefile.win clobber_all
@cd $(MOZ_SRC)\$(MOZ_TOP)\js\src\xpconnect
nmake -f makefile.win clobber_all
clobber_seamonkey:
@cd $(MOZ_SRC)\$(MOZ_TOP)\.
-rd /s /q dist
nmake -f makefile.win clobber_all
depend: export
@cd $(MOZ_SRC)\$(MOZ_TOP)\.
nmake -f makefile.win depend
depend_xpconnect:
@cd $(MOZ_SRC)\$(MOZ_TOP)\include
nmake -f makefile.win depend
@cd $(MOZ_SRC)\$(MOZ_TOP)\modules\libreg
nmake -f makefile.win depend
@cd $(MOZ_SRC)\$(MOZ_TOP)\string
nmake -f makefile.win depend
@cd $(MOZ_SRC)\$(MOZ_TOP)\xpcom
nmake -f makefile.win depend
@cd $(MOZ_SRC)\$(MOZ_TOP)\js\src
nmake -f makefile.win depend
@cd $(MOZ_SRC)\$(MOZ_TOP)\js\src\xpconnect
nmake -f makefile.win depend
build_nspr:
@cd $(MOZ_SRC)\$(MOZ_TOP)\nsprpub
gmake -f gmakefile.win MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED)
build_ldapcsdk:
@cd $(MOZ_SRC)\$(MOZ_TOP)\directory\c-sdk
gmake -f gmakefile.win MOZ_SRC_FLIPPED=$(MOZ_SRC_FLIPPED) SHELL=sh
build_psm:
@cd $(MOZ_SRC)\$(MOZ_TOP)\security
nmake -f makefile.win
build_xpconnect: build_nspr
@cd $(MOZ_SRC)\$(MOZ_TOP)\include
nmake -f makefile.win all
@cd $(MOZ_SRC)\$(MOZ_TOP)\modules\libreg
nmake -f makefile.win all
@cd $(MOZ_SRC)\$(MOZ_TOP)\xpcom
nmake -f makefile.win export
@cd $(MOZ_SRC)\$(MOZ_TOP)\string
nmake -f makefile.win all
@cd $(MOZ_SRC)\$(MOZ_TOP)\xpcom
nmake -f makefile.win libs
@cd $(MOZ_SRC)\$(MOZ_TOP)\js\src
nmake -f makefile.win all
@cd $(MOZ_SRC)\$(MOZ_TOP)\js\src\xpconnect
nmake -f makefile.win all
build_seamonkey:
@cd $(MOZ_SRC)\$(MOZ_TOP)\.
nmake -f makefile.win all
build_client:
@cd $(MOZ_SRC)\mozilla\.
nmake -f makefile.win all
build_layout:
@cd $(MOZ_SRC)\mozilla\.
nmake -f makefile.win all
build_dist:
@cd $(MOZ_SRC)\mozilla\.
nmake -f makefile.win all
libs:
@cd $(MOZ_SRC)\$(MOZ_TOP)\.
nmake -f makefile.win libs
export: build_nspr build_ldapcsdk
@cd $(MOZ_SRC)\$(MOZ_TOP)\.
nmake -f makefile.win export
clobber_dist:
@cd $(MOZ_SRC)\mozilla\.
nmake -f makefile.win clobber_all
clobber_client:
@cd $(MOZ_SRC)\mozilla\.
nmake -f makefile.win clobber_all
clobber_layout:
@cd $(MOZ_SRC)\mozilla\.
nmake -f makefile.win clobber_all
browse_info::
cd $(MOZ_SRC)\$(MOZ_TOP)
-dir /s /b *.sbr > sbrlist.tmp
-bscmake /Es /o mozilla.bsc @sbrlist.tmp
-rm sbrlist.tmp
regchrome::
@cd $(MOZ_SRC)\mozilla\.
nmake /f makefile.win regchrome
deliver::
@cd $(MOZ_SRC)\mozilla\.
nmake /f makefile.win splitsymbols
#//------------------------------------------------------------------------
#// Utility stuff...
#//------------------------------------------------------------------------
#//------------------------------------------------------------------------
# Verify that MOZ_SRC is set correctly
#//------------------------------------------------------------------------
# Check to see if it is set at all
!if "$(MOZ_SRC)"==""
MOZ_SRC = $(MAKEDIR)\..
!endif
#
# create a temp file at the root and make sure it is visible from MOZ_SRC
#
!if [copy $(MAKEDIR)\client.mak $(MAKEDIR)\xyzzy.tmp > NUL] == 0
!endif
!if !EXIST( $(MOZ_SRC)\mozilla\xyzzy.tmp )
ERR_MESSAGE=$(ERR_MESSAGE)^
MOZ_SRC isn't set correctly: [$(MOZ_SRC)\mozilla]!=[$(MAKEDIR)]
!endif
!if [del $(MAKEDIR)\xyzzy.tmp]
!endif
#//------------------------------------------------------------------------
# Verify that MOZ_BITS is set
#//------------------------------------------------------------------------
!if !defined(MOZ_BITS)
ERR_MESSAGE=$(ERR_MESSAGE)^
Environment variable MOZ_BITS isn't set.
!endif
!if !defined(MOZ_TOOLS)
ERR_MESSAGE=$(ERR_MESSAGE)^
Environment variable MOZ_TOOLS isn't set.
!endif
#//------------------------------------------------------------------------
#// Display error
#//------------------------------------------------------------------------
!if "$(ERR_MESSAGE)" != ""
ERR_MESSAGE = ^
client.mak: ^
$(ERR_MESSAGE) ^
^
client.mak: usage^
^
nmake -f client.mak [MOZ_BRANCH=<cvs_branch_name>] ^
[MOZ_DATE=<cvs_date>]^
[pull_and_build_all]^
[pull_all]^
[build_all]^
^
Environment variables:^
^
MOZ_BITS set to 32^
MOZ_TOOLS set to the directory containing the needed tools ^
!ERROR $(ERR_MESSAGE)
!endif

View File

@@ -1,650 +0,0 @@
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Stephen Lamm
# Build the Mozilla client.
#
# This needs CVSROOT set to work, e.g.,
# setenv CVSROOT :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot
# or
# setenv CVSROOT :pserver:username%somedomain.org@cvs.mozilla.org:/cvsroot
#
# To checkout and build a tree,
# 1. cvs co mozilla/client.mk
# 2. cd mozilla
# 3. gmake -f client.mk
#
# Other targets (gmake -f client.mk [targets...]),
# checkout
# build
# clean (realclean is now the same as clean)
# distclean
#
# See http://www.mozilla.org/build/unix.html for more information.
#
# Options:
# MOZ_OBJDIR - Destination object directory
# MOZ_CO_DATE - Date tag to use for checkout (default: none)
# MOZ_CO_MODULE - Module to checkout (default: SeaMonkeyAll)
# MOZ_CVS_FLAGS - Flags to pass cvs (default: -q -z3)
# MOZ_CO_FLAGS - Flags to pass after 'cvs co' (default: -P)
# MOZ_MAKE_FLAGS - Flags to pass to $(MAKE)
# MOZ_CO_BRANCH - Branch tag (Deprecated. Use MOZ_CO_TAG below.)
#
#######################################################################
# Checkout Tags
#
# For branches, uncomment the MOZ_CO_TAG line with the proper tag,
# and commit this file on that tag.
MOZ_CO_TAG = NETSCAPE_7_0_RTM
NSPR_CO_TAG = NETSCAPE_7_0_RTM
PSM_CO_TAG = NETSCAPE_7_0_RTM
NSS_CO_TAG = NETSCAPE_7_0_RTM
LDAPCSDK_CO_TAG = NETSCAPE_7_0_RTM
ACCESSIBLE_CO_TAG = NETSCAPE_7_0_RTM
GFX2_CO_TAG = NETSCAPE_7_0_RTM
IMGLIB2_CO_TAG = NETSCAPE_7_0_RTM
BUILD_MODULES = all
#######################################################################
# Defines
#
CVS = cvs
CWD := $(shell pwd)
ifeq "$(CWD)" "/"
CWD := /.
endif
ifneq (, $(wildcard client.mk))
# Ran from mozilla directory
ROOTDIR := $(shell dirname $(CWD))
TOPSRCDIR := $(CWD)
else
# Ran from mozilla/.. directory (?)
ROOTDIR := $(CWD)
TOPSRCDIR := $(CWD)/mozilla
endif
# on os2, TOPSRCDIR may have two forward slashes in a row, which doesn't
# work; replace first instance with one forward slash
TOPSRCDIR := $(shell echo "$(TOPSRCDIR)" | sed -e 's%//%/%')
ifndef TOPSRCDIR_MOZ
TOPSRCDIR_MOZ=$(TOPSRCDIR)
endif
# if ROOTDIR equals only drive letter (i.e. "C:"), set to "/"
DIRNAME := $(shell echo "$(ROOTDIR)" | sed -e 's/^.://')
ifeq ($(DIRNAME),)
ROOTDIR := /.
endif
AUTOCONF := autoconf
MKDIR := mkdir
SH := /bin/sh
ifndef MAKE
MAKE := gmake
endif
CONFIG_GUESS_SCRIPT := $(wildcard $(TOPSRCDIR)/build/autoconf/config.guess)
ifdef CONFIG_GUESS_SCRIPT
CONFIG_GUESS = $(shell $(CONFIG_GUESS_SCRIPT))
else
_IS_FIRST_CHECKOUT := 1
endif
####################################
# CVS
# Add the CVS root to CVS_FLAGS if needed
CVS_ROOT_IN_TREE := $(shell cat $(TOPSRCDIR)/CVS/Root 2>/dev/null)
ifneq ($(CVS_ROOT_IN_TREE),)
ifneq ($(CVS_ROOT_IN_TREE),$(CVSROOT))
CVS_FLAGS := -d $(CVS_ROOT_IN_TREE)
endif
endif
CVSCO = $(strip $(CVS) $(CVS_FLAGS) co $(CVS_CO_FLAGS))
CVSCO_LOGFILE := $(ROOTDIR)/cvsco.log
CVSCO_LOGFILE := $(shell echo $(CVSCO_LOGFILE) | sed s%//%/%)
ifdef MOZ_CO_TAG
CVS_CO_FLAGS := -r $(MOZ_CO_TAG)
endif
####################################
# Load mozconfig Options
# See build pages, http://www.mozilla.org/build/unix.html,
# for how to set up mozconfig.
MOZCONFIG_LOADER := mozilla/build/autoconf/mozconfig2client-mk
MOZCONFIG_FINDER := mozilla/build/autoconf/mozconfig-find
MOZCONFIG_MODULES := mozilla/build/unix/modules.mk
run_for_side_effects := \
$(shell cd $(ROOTDIR); \
if test "$(_IS_FIRST_CHECKOUT)"; then \
$(CVSCO) $(MOZCONFIG_FINDER) $(MOZCONFIG_LOADER) $(MOZCONFIG_MODULES); \
else true; \
fi; \
$(MOZCONFIG_LOADER) $(TOPSRCDIR) mozilla/.mozconfig.mk > mozilla/.mozconfig.out)
include $(TOPSRCDIR)/.mozconfig.mk
include $(TOPSRCDIR)/build/unix/modules.mk
####################################
# Options that may come from mozconfig
# Change CVS flags if anonymous root is requested
ifdef MOZ_CO_USE_MIRROR
CVS_FLAGS := -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot
endif
# MOZ_CVS_FLAGS - Basic CVS flags
ifeq "$(origin MOZ_CVS_FLAGS)" "undefined"
CVS_FLAGS := $(CVS_FLAGS) -q -z 3
else
CVS_FLAGS := $(MOZ_CVS_FLAGS)
endif
# This option is deprecated. The best way to have client.mk pull a tag
# is to set MOZ_CO_TAG (see above) and commit that change on the tag.
ifdef MOZ_CO_BRANCH
$(warning Use MOZ_CO_TAG instead of MOZ_CO_BRANCH)
CVS_CO_FLAGS := -r $(MOZ_CO_BRANCH)
endif
# MOZ_CO_FLAGS - Anything that we should use on all checkouts
ifeq "$(origin MOZ_CO_FLAGS)" "undefined"
CVS_CO_FLAGS := $(CVS_CO_FLAGS) -P
else
CVS_CO_FLAGS := $(CVS_CO_FLAGS) $(MOZ_CO_FLAGS)
endif
ifdef MOZ_CO_DATE
CVS_CO_DATE_FLAGS := -D "$(MOZ_CO_DATE)"
endif
ifdef MOZ_OBJDIR
OBJDIR := $(MOZ_OBJDIR)
MOZ_MAKE := $(MAKE) $(MOZ_MAKE_FLAGS) -C $(OBJDIR)
else
OBJDIR := $(TOPSRCDIR)
MOZ_MAKE := $(MAKE) $(MOZ_MAKE_FLAGS)
endif
####################################
# CVS defines for PSM
#
PSM_CO_MODULE= mozilla/security/manager
PSM_CO_FLAGS := -P -A
ifdef MOZ_CO_FLAGS
PSM_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef PSM_CO_TAG
PSM_CO_FLAGS := $(PSM_CO_FLAGS) -r $(PSM_CO_TAG)
endif
CVSCO_PSM = $(CVS) $(CVS_FLAGS) co $(PSM_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(PSM_CO_MODULE)
####################################
# CVS defines for NSS
#
NSS_CO_MODULE = mozilla/security/nss \
mozilla/security/coreconf \
$(NULL)
NSS_CO_FLAGS := -P
ifdef MOZ_CO_FLAGS
NSS_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef NSS_CO_TAG
NSS_CO_FLAGS := $(NSS_CO_FLAGS) -r $(NSS_CO_TAG)
endif
# Cannot pull static tags by date
ifeq ($(NSS_CO_TAG),NSS_CLIENT_TAG)
CVSCO_NSS = $(CVS) $(CVS_FLAGS) co $(NSS_CO_FLAGS) $(NSS_CO_MODULE)
else
CVSCO_NSS = $(CVS) $(CVS_FLAGS) co $(NSS_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(NSS_CO_MODULE)
endif
####################################
# CVS defines for NSPR
#
NSPR_CO_MODULE = mozilla/nsprpub
NSPR_CO_FLAGS := -P
ifdef MOZ_CO_FLAGS
NSPR_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef NSPR_CO_TAG
NSPR_CO_FLAGS := $(NSPR_CO_FLAGS) -r $(NSPR_CO_TAG)
endif
# Cannot pull static tags by date
ifeq ($(NSPR_CO_TAG),NSPRPUB_CLIENT_TAG)
CVSCO_NSPR = $(CVS) $(CVS_FLAGS) co $(NSPR_CO_FLAGS) $(NSPR_CO_MODULE)
else
CVSCO_NSPR = $(CVS) $(CVS_FLAGS) co $(NSPR_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(NSPR_CO_MODULE)
endif
####################################
# CVS defines for the C LDAP SDK
#
LDAPCSDK_CO_MODULE = mozilla/directory/c-sdk
LDAPCSDK_CO_FLAGS := -P
ifdef MOZ_CO_FLAGS
LDAPCSDK_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef LDAPCSDK_CO_TAG
LDAPCSDK_CO_FLAGS := $(LDAPCSDK_CO_FLAGS) -r $(LDAPCSDK_CO_TAG)
endif
CVSCO_LDAPCSDK = $(CVS) $(CVS_FLAGS) co $(LDAPCSDK_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(LDAPCSDK_CO_MODULE)
####################################
# CVS defines for the C LDAP SDK
#
ACCESSIBLE_CO_MODULE = mozilla/accessible
ACCESSIBLE_CO_FLAGS := -P
ifdef MOZ_CO_FLAGS
ACCESSIBLE_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef ACCESSIBLE_CO_TAG
ACCESSIBLE_CO_FLAGS := $(ACCESSIBLE_CO_FLAGS) -r $(ACCESSIBLE_CO_TAG)
endif
CVSCO_ACCESSIBLE = $(CVS) $(CVS_FLAGS) co $(ACCESSIBLE_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(ACCESSIBLE_CO_MODULE)
####################################
# CVS defines for gfx2
#
GFX2_CO_MODULE = mozilla/gfx2
GFX2_CO_FLAGS := -P
ifdef MOZ_CO_FLAGS
GFX2_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef GFX2_CO_TAG
GFX2_CO_FLAGS := $(GFX2_CO_FLAGS) -r $(GFX2_CO_TAG)
endif
CVSCO_GFX2 = $(CVS) $(CVS_FLAGS) co $(GFX2_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(GFX2_CO_MODULE)
####################################
# CVS defines for new image library
#
IMGLIB2_CO_MODULE = mozilla/modules/libpr0n
IMGLIB2_CO_FLAGS := -P
ifdef MOZ_CO_FLAGS
IMGLIB2_CO_FLAGS := $(MOZ_CO_FLAGS)
endif
ifdef IMGLIB2_CO_TAG
IMGLIB2_CO_FLAGS := $(IMGLIB2_CO_FLAGS) -r $(IMGLIB2_CO_TAG)
endif
CVSCO_IMGLIB2 = $(CVS) $(CVS_FLAGS) co $(IMGLIB2_CO_FLAGS) $(CVS_CO_DATE_FLAGS) $(IMGLIB2_CO_MODULE)
####################################
# CVS defines for standalone modules
#
ifneq ($(BUILD_MODULES),all)
MOZ_CO_MODULE := $(filter-out $(NSPRPUB_DIR) security directory/c-sdk, $(BUILD_MODULE_CVS))
MOZ_CO_MODULE += allmakefiles.sh client.mk aclocal.m4 configure configure.in
MOZ_CO_MODULE += Makefile.in
MOZ_CO_MODULE := $(addprefix mozilla/, $(MOZ_CO_MODULE))
NOSUBDIRS_MODULE := $(addprefix mozilla/, $(BUILD_MODULE_CVS_NS))
ifneq ($(NOSUBDIRS_MODULE),)
CVSCO_NOSUBDIRS := $(CVSCO) -l $(CVS_CO_DATE_FLAGS) $(NOSUBDIRS_MODULE)
endif
ifeq (,$(filter $(NSPRPUB_DIR), $(BUILD_MODULE_CVS)))
CVSCO_NSPR :=
endif
ifeq (,$(filter security security/manager, $(BUILD_MODULE_CVS)))
CVSCO_PSM :=
CVSCO_NSS :=
endif
ifeq (,$(filter directory/c-sdk, $(BUILD_MODULE_CVS)))
CVSCO_LDAPCSDK :=
endif
ifeq (,$(filter accessible, $(BUILD_MODULE_CVS)))
CVSCO_ACCESSIBLE :=
endif
ifeq (,$(filter gfx2, $(BUILD_MODULE_CVS)))
CVSCO_GFX2 :=
endif
ifeq (,$(filter modules/libpr0n, $(BUILD_MODULE_CVS)))
CVSCO_IMGLIB2 :=
endif
endif
####################################
# CVS defines for SeaMonkey
#
ifeq ($(MOZ_CO_MODULE),)
MOZ_CO_MODULE := SeaMonkeyAll
endif
CVSCO_SEAMONKEY := $(CVSCO) $(CVS_CO_DATE_FLAGS) $(MOZ_CO_MODULE)
####################################
# CVS defined for libart (pulled and built if MOZ_INTERNAL_LIBART_LGPL is set)
#
CVSCO_LIBART := $(CVSCO) $(CVS_CO_DATE_FLAGS) mozilla/other-licenses/libart_lgpl
ifdef MOZ_INTERNAL_LIBART_LGPL
FASTUPDATE_LIBART := fast_update $(CVSCO_LIBART)
CHECKOUT_LIBART := cvs_co $(CVSCO_LIBART)
else
CHECKOUT_LIBART := true
FASTUPDATE_LIBART := true
endif
####################################
# CVS defines for Calendar (pulled and built if MOZ_CALENDAR is set)
#
CVSCO_CALENDAR := $(CVSCO) $(CVS_CO_DATE_FLAGS) mozilla/calendar
ifdef MOZ_CALENDAR
FASTUPDATE_CALENDAR := fast_update $(CVSCO_CALENDAR)
CHECKOUT_CALENDAR := cvs_co $(CVSCO_CALENDAR)
else
CHECKOUT_CALENDAR := true
FASTUPDATE_CALENDAR := true
endif
# because some cygwin tools can't handle native dos-drive paths & vice-versa
# force configure to use a relative path for --srcdir
# need a better check for win32
# and we need to get OBJDIR earlier
ifdef MOZ_TOOLS
_tmpobjdir := $(shell cygpath -u $(OBJDIR))
_abs2rel := $(shell cygpath -w $(TOPSRCDIR)/build/unix/abs2rel.pl | sed -e 's|\\|/|g')
_OBJ2SRCPATH := $(shell $(_abs2rel) $(TOPSRCDIR) $(_tmpobjdir))
endif
#######################################################################
# Rules
#
# Print out any options loaded from mozconfig.
all build checkout clean depend distclean export libs install realclean::
@if test -f .mozconfig.out; then \
cat .mozconfig.out; \
rm -f .mozconfig.out; \
else true; \
fi
ifdef _IS_FIRST_CHECKOUT
all:: checkout build
else
all:: checkout alldep
endif
# Windows equivalents
pull_all: checkout
build_all: build
build_all_dep: alldep
build_all_depend: alldep
clobber clobber_all: clean
pull_and_build_all: checkout alldep
# Do everything from scratch
everything: checkout clean build
####################################
# CVS checkout
#
checkout::
# @: Backup the last checkout log.
@if test -f $(CVSCO_LOGFILE) ; then \
mv $(CVSCO_LOGFILE) $(CVSCO_LOGFILE).old; \
else true; \
fi
ifdef RUN_AUTOCONF_LOCALLY
@echo "Removing local configures" ; \
cd $(ROOTDIR) && \
$(RM) -f mozilla/configure mozilla/nsprpub/configure \
mozilla/directory/c-sdk/configure
endif
@echo "checkout start: "`date` | tee $(CVSCO_LOGFILE)
@echo '$(CVSCO) mozilla/client.mk mozilla/build/unix/modules.mk'; \
cd $(ROOTDIR) && \
$(CVSCO) mozilla/client.mk mozilla/build/unix/modules.mk
@cd $(ROOTDIR) && $(MAKE) -f mozilla/client.mk real_checkout
real_checkout:
# @: Start the checkout. Split the output to the tty and a log file. \
# : If it fails, touch an error file because "tee" hides the error.
@failed=.cvs-failed.tmp; rm -f $$failed*; \
cvs_co() { echo "$$@" ; \
("$$@" || touch $$failed) 2>&1 | tee -a $(CVSCO_LOGFILE) && \
if test -f $$failed; then false; else true; fi; }; \
cvs_co $(CVSCO_NSPR) && \
cvs_co $(CVSCO_NSS) && \
cvs_co $(CVSCO_PSM) && \
cvs_co $(CVSCO_LDAPCSDK) && \
cvs_co $(CVSCO_ACCESSIBLE) && \
cvs_co $(CVSCO_GFX2) && \
cvs_co $(CVSCO_IMGLIB2) && \
$(CHECKOUT_CALENDAR) && \
$(CHECKOUT_LIBART) && \
cvs_co $(CVSCO_SEAMONKEY) && \
cvs_co $(CVSCO_NOSUBDIRS)
@echo "checkout finish: "`date` | tee -a $(CVSCO_LOGFILE)
# @: Check the log for conflicts. ;
@conflicts=`egrep "^C " $(CVSCO_LOGFILE)` ;\
if test "$$conflicts" ; then \
echo "$(MAKE): *** Conflicts during checkout." ;\
echo "$$conflicts" ;\
echo "$(MAKE): Refer to $(CVSCO_LOGFILE) for full log." ;\
false; \
else true; \
fi
ifdef RUN_AUTOCONF_LOCALLY
@echo Generating configures using $(AUTOCONF) ; \
cd $(TOPSRCDIR) && $(AUTOCONF) && \
cd $(TOPSRCDIR)/nsprpub && $(AUTOCONF) && \
cd $(TOPSRCDIR)/directory/c-sdk && $(AUTOCONF)
endif
fast-update:
# @: Backup the last checkout log.
@if test -f $(CVSCO_LOGFILE) ; then \
mv $(CVSCO_LOGFILE) $(CVSCO_LOGFILE).old; \
else true; \
fi
ifdef RUN_AUTOCONF_LOCALLY
@echo "Removing local configures" ; \
cd $(ROOTDIR) && \
$(RM) -f mozilla/configure mozilla/nsprpub/configure \
mozilla/directory/c-sdk/configure
endif
@echo "checkout start: "`date` | tee $(CVSCO_LOGFILE)
@echo '$(CVSCO) mozilla/client.mk mozilla/build/unix/modules.mk'; \
cd $(ROOTDIR) && \
$(CVSCO) mozilla/client.mk mozilla/build/unix/modules.mk
@cd $(TOPSRCDIR) && \
$(MAKE) -f client.mk real_fast-update
real_fast-update:
# @: Start the update. Split the output to the tty and a log file. \
# : If it fails, touch an error file because "tee" hides the error.
@failed=.fast_update-failed.tmp; rm -f $$failed*; \
fast_update() { (config/cvsco-fast-update.pl $$@ || touch $$failed) 2>&1 | tee -a $(CVSCO_LOGFILE) && \
if test -f $$failed; then false; else true; fi; }; \
cvs_co() { echo "$$@" ; \
("$$@" || touch $$failed) 2>&1 | tee -a $(CVSCO_LOGFILE) && \
if test -f $$failed; then false; else true; fi; }; \
fast_update $(CVSCO_NSPR) && \
cd $(ROOTDIR) && \
failed=mozilla/.fast_update-failed.tmp && \
cvs_co $(CVSCO_NSS) && \
failed=.fast_update-failed.tmp && \
cd mozilla && \
fast_update $(CVSCO_PSM) && \
fast_update $(CVSCO_LDAPCSDK) && \
fast_update $(CVSCO_ACCESSIBLE) && \
fast_update $(CVSCO_GFX2) && \
fast_update $(CVSCO_IMGLIB2) && \
$(FASTUPDATE_CALENDAR) && \
$(FASTUPDATE_LIBART) && \
fast_update $(CVSCO_SEAMONKEY) && \
fast_update $(CVSCO_NOSUBDIRS)
@echo "fast_update finish: "`date` | tee -a $(CVSCO_LOGFILE)
# @: Check the log for conflicts. ;
@conflicts=`egrep "^C " $(CVSCO_LOGFILE)` ;\
if test "$$conflicts" ; then \
echo "$(MAKE): *** Conflicts during fast-update." ;\
echo "$$conflicts" ;\
echo "$(MAKE): Refer to $(CVSCO_LOGFILE) for full log." ;\
false; \
else true; \
fi
ifdef RUN_AUTOCONF_LOCALLY
@echo Generating configures using $(AUTOCONF) ; \
cd $(TOPSRCDIR) && $(AUTOCONF) && \
cd $(TOPSRCDIR)/nsprpub && $(AUTOCONF) && \
cd $(TOPSRCDIR)/directory/c-sdk && $(AUTOCONF)
endif
####################################
# Web configure
WEBCONFIG_FILE := $(HOME)/.mozconfig
MOZCONFIG2CONFIGURATOR := build/autoconf/mozconfig2configurator
webconfig:
@cd $(TOPSRCDIR); \
url=`$(MOZCONFIG2CONFIGURATOR) $(TOPSRCDIR)`; \
echo Running mozilla with the following url: ;\
echo ;\
echo $$url ;\
mozilla -remote "openURL($$url)" || \
netscape -remote "openURL($$url)" || \
mozilla $$url || \
netscape $$url ;\
echo ;\
echo 1. Fill out the form on the browser. ;\
echo 2. Save the results to $(WEBCONFIG_FILE)
#####################################################
# First Checkout
ifdef _IS_FIRST_CHECKOUT
# First time, do build target in a new process to pick up new files.
build::
$(MAKE) -f $(TOPSRCDIR)/client.mk build
else
#####################################################
# After First Checkout
####################################
# Configure
CONFIG_STATUS := $(wildcard $(OBJDIR)/config.status)
CONFIG_CACHE := $(wildcard $(OBJDIR)/config.cache)
ifdef RUN_AUTOCONF_LOCALLY
EXTRA_CONFIG_DEPS := \
$(TOPSRCDIR)/aclocal.m4 \
$(wildcard $(TOPSRCDIR)/build/autoconf/*.m4) \
$(NULL)
$(TOPSRCDIR)/configure: $(TOPSRCDIR)/configure.in $(EXTRA_CONFIG_DEPS)
@echo Generating $@ using autoconf
cd $(TOPSRCDIR); $(AUTOCONF)
endif
CONFIG_STATUS_DEPS_L10N := $(wildcard $(TOPSRCDIR)/l10n/makefiles.all)
CONFIG_STATUS_DEPS := \
$(TOPSRCDIR)/configure \
$(TOPSRCDIR)/allmakefiles.sh \
$(TOPSRCDIR)/.mozconfig.mk \
$(wildcard $(TOPSRCDIR)/nsprpub/configure) \
$(wildcard $(TOPSRCDIR)/directory/c-sdk/configure) \
$(wildcard $(TOPSRCDIR)/mailnews/makefiles) \
$(CONFIG_STATUS_DEPS_L10N) \
$(wildcard $(TOPSRCDIR)/themes/makefiles) \
$(NULL)
# configure uses the program name to determine @srcdir@. Calling it without
# $(TOPSRCDIR) will set @srcdir@ to "."; otherwise, it is set to the full
# path of $(TOPSRCDIR).
ifeq ($(TOPSRCDIR),$(OBJDIR))
CONFIGURE := ./configure
else
CONFIGURE := $(TOPSRCDIR)/configure
endif
ifdef _OBJ2SRCPATH
CONFIGURE_ARGS := --srcdir=$(_OBJ2SRCPATH) $(CONFIGURE_ARGS)
endif
$(OBJDIR)/Makefile $(OBJDIR)/config.status: $(CONFIG_STATUS_DEPS)
@if test ! -d $(OBJDIR); then $(MKDIR) $(OBJDIR); else true; fi
@echo cd $(OBJDIR);
@echo $(CONFIGURE) $(CONFIGURE_ARGS)
@cd $(OBJDIR) && $(CONFIGURE_ENV_ARGS) $(CONFIGURE) $(CONFIGURE_ARGS) \
|| ( echo "*** Fix above errors and then restart with\
\"$(MAKE) -f client.mk build\"" && exit 1 )
@touch $(OBJDIR)/Makefile
ifdef CONFIG_STATUS
$(OBJDIR)/config/autoconf.mk: $(TOPSRCDIR)/config/autoconf.mk.in
cd $(OBJDIR); \
CONFIG_FILES=config/autoconf.mk ./config.status
endif
####################################
# Depend
depend:: $(OBJDIR)/Makefile $(OBJDIR)/config.status
$(MOZ_MAKE) export && $(MOZ_MAKE) depend
####################################
# Build it
build:: $(OBJDIR)/Makefile $(OBJDIR)/config.status
$(MOZ_MAKE)
####################################
# Other targets
# Pass these target onto the real build system
install export libs clean realclean distclean alldep:: $(OBJDIR)/Makefile $(OBJDIR)/config.status
$(MOZ_MAKE) $@
cleansrcdir:
@cd $(TOPSRCDIR); \
if [ -f webshell/embed/gtk/Makefile ]; then \
$(MAKE) -C webshell/embed/gtk distclean; \
fi; \
if [ -f Makefile ]; then \
$(MAKE) distclean ; \
else \
echo "Removing object files from srcdir..."; \
rm -fr `find . -type d \( -name .deps -print -o -name CVS \
-o -exec test ! -d {}/CVS \; \) -prune \
-o \( -name '*.[ao]' -o -name '*.so' \) -type f -print`; \
build/autoconf/clean-config.sh; \
fi;
# (! IS_FIRST_CHECKOUT)
endif
.PHONY: checkout real_checkout depend build export libs alldep install clean realclean distclean cleansrcdir pull_all build_all clobber clobber_all pull_and_build_all everything

View File

@@ -0,0 +1,35 @@
#!gmake
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (the "NPL"); you may not use this file except in
# compliance with the NPL. You may obtain a copy of the NPL at
# http://www.mozilla.org/NPL/
#
# Software distributed under the NPL is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
# for the specific language governing rights and limitations under the
# NPL.
#
# The Initial Developer of this code under the NPL is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All Rights
# Reserved.
DEPTH = ..
topsrcdir = @top_srcdir@
VPATH = @srcdir@
srcdir = @srcdir@
include $(DEPTH)/config/autoconf.mk
DIRS = public idl
ifdef MOZ_EDITOR
DIRS += base ui
endif
DIRS += txmgr txtsvc
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk

View File

@@ -0,0 +1,130 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "ChangeAttributeTxn.h"
#include "nsIDOMElement.h"
#include "nsEditor.h"
ChangeAttributeTxn::ChangeAttributeTxn()
: EditTxn()
{
}
ChangeAttributeTxn::~ChangeAttributeTxn()
{
}
NS_IMETHODIMP ChangeAttributeTxn::Init(nsIEditor *aEditor,
nsIDOMElement *aElement,
const nsString& aAttribute,
const nsString& aValue,
PRBool aRemoveAttribute)
{
if (nsnull!=aEditor && nsnull!=aElement)
{
mEditor = aEditor;
mElement = do_QueryInterface(aElement);
mAttribute = aAttribute;
mValue = aValue;
mRemoveAttribute = aRemoveAttribute;
mAttributeWasSet=PR_FALSE;
mUndoValue="";
return NS_OK;
}
else
return NS_ERROR_NULL_POINTER;
}
NS_IMETHODIMP ChangeAttributeTxn::Do(void)
{
// need to get the current value of the attribute and save it, and set mAttributeWasSet
nsresult result = mEditor->GetAttributeValue(mElement, mAttribute, mUndoValue, mAttributeWasSet);
// XXX: hack until attribute-was-set code is implemented
if (PR_FALSE==mUndoValue.Equals(""))
mAttributeWasSet=PR_TRUE;
// XXX: end hack
// now set the attribute to the new value
if (PR_FALSE==mRemoveAttribute)
result = mElement->SetAttribute(mAttribute, mValue);
else
result = mElement->RemoveAttribute(mAttribute);
return result;
}
NS_IMETHODIMP ChangeAttributeTxn::Undo(void)
{
nsresult result=NS_OK;
if (PR_TRUE==mAttributeWasSet)
result = mElement->SetAttribute(mAttribute, mUndoValue);
else
result = mElement->RemoveAttribute(mAttribute);
return result;
}
NS_IMETHODIMP ChangeAttributeTxn::Redo(void)
{
nsresult result;
if (PR_FALSE==mRemoveAttribute)
result = mElement->SetAttribute(mAttribute, mValue);
else
result = mElement->RemoveAttribute(mAttribute);
return result;
}
NS_IMETHODIMP ChangeAttributeTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
if (nsnull!=aDidMerge)
*aDidMerge=PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP ChangeAttributeTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP ChangeAttributeTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
{
if (PR_FALSE==mRemoveAttribute)
*aString="Change Attribute: ";
else
*aString="Remove Attribute: ";
*aString += mAttribute;
}
return NS_OK;
}
NS_IMETHODIMP ChangeAttributeTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
{
if (PR_FALSE==mRemoveAttribute)
*aString="Change Attribute: ";
else
*aString="Add Attribute: ";
*aString += mAttribute;
}
return NS_OK;
}

View File

@@ -0,0 +1,102 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef ChangeAttributeTxn_h__
#define ChangeAttributeTxn_h__
#include "EditTxn.h"
#include "nsCOMPtr.h"
#include "nsIDOMElement.h"
#include "nsIEditor.h"
#define CHANGE_ATTRIBUTE_TXN_CID \
{/* 97818860-ac48-11d2-86d8-000064657374 */ \
0x97818860, 0xac48, 0x11d2, \
{0x86, 0xd8, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74} }
/**
* A transaction that changes an attribute of a content node.
* This transaction covers add, remove, and change attribute.
*/
class ChangeAttributeTxn : public EditTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = CHANGE_ATTRIBUTE_TXN_CID; return iid; }
virtual ~ChangeAttributeTxn();
/** Initialize the transaction.
* @param aEditor the object providing core editing operations
* @param aNode the node whose attribute will be changed
* @param aAttribute the name of the attribute to change
* @param aValue the new value for aAttribute, if aRemoveAttribute is false
* @param aRemoveAttribute if PR_TRUE, remove aAttribute from aNode
*/
NS_IMETHOD Init(nsIEditor *aEditor,
nsIDOMElement *aNode,
const nsString& aAttribute,
const nsString& aValue,
PRBool aRemoveAttribute);
private:
ChangeAttributeTxn();
public:
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Redo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
protected:
/** the editor that created this transaction */
nsIEditor* mEditor;
/** the element to operate upon */
nsCOMPtr<nsIDOMElement> mElement;
/** the attribute to change */
nsString mAttribute;
/** the value to set the attribute to (ignored if mRemoveAttribute==PR_TRUE) */
nsString mValue;
/** the value to set the attribute to for undo */
nsString mUndoValue;
/** PR_TRUE if the mAttribute was set on mElement at the time of execution */
PRBool mAttributeWasSet;
/** PR_TRUE if the operation is to remove mAttribute from mElement */
PRBool mRemoveAttribute;
friend class TransactionFactory;
};
#endif

View File

@@ -0,0 +1,236 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "CreateElementTxn.h"
#include "nsEditor.h"
#include "nsIDOMDocument.h"
#include "nsIDOMNodeList.h"
#include "nsIDOMSelection.h"
#include "nsIDOMText.h"
#include "nsIDOMElement.h"
#ifdef NS_DEBUG
static PRBool gNoisy = PR_FALSE;
#else
static const PRBool gNoisy = PR_FALSE;
#endif
CreateElementTxn::CreateElementTxn()
: EditTxn()
{
}
NS_IMETHODIMP CreateElementTxn::Init(nsIEditor *aEditor,
const nsString &aTag,
nsIDOMNode *aParent,
PRUint32 aOffsetInParent)
{
NS_ASSERTION(aEditor&&aParent, "null args");
if (aEditor && aParent)
{
mEditor = aEditor;
mTag = aTag;
mParent = do_QueryInterface(aParent);
mOffsetInParent = aOffsetInParent;
#ifdef NS_DEBUG
{
nsCOMPtr<nsIDOMNodeList> testChildNodes;
nsresult testResult = mParent->GetChildNodes(getter_AddRefs(testChildNodes));
NS_ASSERTION(testChildNodes, "bad parent type, can't have children.");
NS_ASSERTION(NS_SUCCEEDED(testResult), "bad result.");
}
#endif
return NS_OK;
}
else
return NS_ERROR_NULL_POINTER;
}
CreateElementTxn::~CreateElementTxn()
{
}
NS_IMETHODIMP CreateElementTxn::Do(void)
{
if (gNoisy) { printf("Do Create Element parent = %p, offset = %d\n",
mParent.get(), mOffsetInParent); }
NS_ASSERTION(mEditor, "bad state -- null editor");
nsresult result = NS_ERROR_NULL_POINTER;
if (mEditor)
{
// create a new node
nsCOMPtr<nsIDOMDocument>doc;
result = mEditor->GetDocument(getter_AddRefs(doc));
if ((NS_SUCCEEDED(result)) && (doc))
{
if (nsEditor::GetTextNodeTag() == mTag)
{
const nsString stringData;
nsCOMPtr<nsIDOMText>newTextNode;
result = doc->CreateTextNode(stringData, getter_AddRefs(newTextNode));
if (NS_SUCCEEDED(result) && newTextNode) {
mNewNode = do_QueryInterface(newTextNode);
}
}
else
{
nsCOMPtr<nsIDOMElement>newElement;
result = doc->CreateElement(mTag, getter_AddRefs(newElement));
if (NS_SUCCEEDED(result) && newElement) {
mNewNode = do_QueryInterface(newElement);
}
}
NS_ASSERTION(((NS_SUCCEEDED(result)) && (mNewNode)), "could not create element.");
if ((NS_SUCCEEDED(result)) && (mNewNode))
{
if (gNoisy) { printf(" newNode = %p\n", mNewNode.get()); }
// insert the new node
nsCOMPtr<nsIDOMNode> resultNode;
if (CreateElementTxn::eAppend==(PRInt32)mOffsetInParent)
{
result = mParent->AppendChild(mNewNode, getter_AddRefs(resultNode));
}
else
{
nsCOMPtr<nsIDOMNodeList> childNodes;
result = mParent->GetChildNodes(getter_AddRefs(childNodes));
if ((NS_SUCCEEDED(result)) && (childNodes))
{
PRUint32 count;
childNodes->GetLength(&count);
if (mOffsetInParent>count)
mOffsetInParent = count;
result = childNodes->Item(mOffsetInParent, getter_AddRefs(mRefNode));
if (NS_SUCCEEDED(result)) // note, it's ok for mRefNode to be null. that means append
{
result = mParent->InsertBefore(mNewNode, mRefNode, getter_AddRefs(resultNode));
if (NS_SUCCEEDED(result))
{
nsCOMPtr<nsIDOMSelection> selection;
nsresult selectionResult = mEditor->GetSelection(getter_AddRefs(selection));
if (NS_SUCCEEDED(selectionResult) && selection) {
PRInt32 offset=0;
nsEditor::GetChildOffset(mNewNode, mParent, offset);
selectionResult = selection->Collapse(mParent, offset+1);
NS_ASSERTION((NS_SUCCEEDED(selectionResult)), "selection could not be collapsed after insert.");
}
}
}
}
}
}
}
}
return result;
}
NS_IMETHODIMP CreateElementTxn::Undo(void)
{
if (gNoisy) { printf("Undo Create Element, mParent = %p, node = %p\n",
mParent.get(), mNewNode.get()); }
nsCOMPtr<nsIDOMNode> resultNode;
nsresult result = mParent->RemoveChild(mNewNode, getter_AddRefs(resultNode));
if (NS_SUCCEEDED(result))
{
nsCOMPtr<nsIDOMSelection> selection;
nsresult selectionResult = mEditor->GetSelection(getter_AddRefs(selection));
if (NS_SUCCEEDED(selectionResult) && selection) {
PRInt32 offset=0;
if (mRefNode) {
nsEditor::GetChildOffset(mRefNode, mParent, offset);
}
selectionResult = selection->Collapse(mParent, offset);
NS_ASSERTION((NS_SUCCEEDED(selectionResult)), "selection could not be collapsed after undo of insert.");
}
}
return result;
}
NS_IMETHODIMP CreateElementTxn::Redo(void)
{
if (gNoisy) { printf("Redo Create Element\n"); }
// first, reset mNewNode so it has no attributes or content
nsCOMPtr<nsIDOMCharacterData>nodeAsText;
nodeAsText = do_QueryInterface(mNewNode);
if (nodeAsText)
{
nsAutoString nullString;
nodeAsText->SetData(nullString);
}
// now, reinsert mNewNode
nsCOMPtr<nsIDOMNode> resultNode;
nsresult result = mParent->InsertBefore(mNewNode, mRefNode, getter_AddRefs(resultNode));
if (NS_SUCCEEDED(result))
{
nsCOMPtr<nsIDOMSelection> selection;
result = mEditor->GetSelection(getter_AddRefs(selection));
if (NS_SUCCEEDED(result) && selection) {
PRInt32 offset=0;
nsEditor::GetChildOffset(mNewNode, mParent, offset);
nsresult selectionResult = selection->Collapse(mParent, offset);
NS_ASSERTION((NS_SUCCEEDED(selectionResult)), "selection could not be collapsed after undo of insert.");
}
}
return result;
}
NS_IMETHODIMP CreateElementTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
if (nsnull!=aDidMerge)
*aDidMerge=PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP CreateElementTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP CreateElementTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Remove Element: ";
*aString += mTag;
}
return NS_OK;
}
NS_IMETHODIMP CreateElementTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Create Element: ";
*aString += mTag;
}
return NS_OK;
}
NS_IMETHODIMP CreateElementTxn::GetNewNode(nsIDOMNode **aNewNode)
{
if (!aNewNode)
return NS_ERROR_NULL_POINTER;
if (!mNewNode)
return NS_ERROR_NOT_INITIALIZED;
*aNewNode = mNewNode;
NS_ADDREF(*aNewNode);
return NS_OK;
}

View File

@@ -0,0 +1,102 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef CreateElementTxn_h__
#define CreateElementTxn_h__
#include "EditTxn.h"
#include "nsIEditor.h"
#include "nsIDOMNode.h"
#include "nsCOMPtr.h"
#define CREATE_ELEMENT_TXN_CID \
{/* 7a6393c0-ac48-11d2-86d8-000064657374 */ \
0x7a6393c0, 0xac48, 0x11d2, \
{0x86, 0xd8, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74} }
/**
* A transaction that creates a new node in the content tree.
*/
class CreateElementTxn : public EditTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = CREATE_ELEMENT_TXN_CID; return iid; }
enum { eAppend=-1 };
/** Initialize the transaction.
* @param aEditor the provider of basic editing functionality
* @param aTag the tag (P, HR, TABLE, etc.) for the new element
* @param aParent the node into which the new element will be inserted
* @param aOffsetInParent the location in aParent to insert the new element
* if eAppend, the new element is appended as the last child
*/
NS_IMETHOD Init(nsIEditor *aEditor,
const nsString& aTag,
nsIDOMNode *aParent,
PRUint32 aOffsetInParent);
private:
CreateElementTxn();
public:
virtual ~CreateElementTxn();
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Redo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
NS_IMETHOD GetNewNode(nsIDOMNode **aNewNode);
protected:
/** the document into which the new node will be inserted */
nsIEditor* mEditor;
/** the tag (mapping to object type) for the new element */
nsString mTag;
/** the node into which the new node will be inserted */
nsCOMPtr<nsIDOMNode> mParent;
/** the index in mParent for the new node */
PRUint32 mOffsetInParent;
/** the new node to insert */
nsCOMPtr<nsIDOMNode> mNewNode;
/** the node we will insert mNewNode before. We compute this ourselves. */
nsCOMPtr<nsIDOMNode> mRefNode;
friend class TransactionFactory;
};
#endif

View File

@@ -0,0 +1,174 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "DeleteElementTxn.h"
#ifdef NS_DEBUG
#include "nsIDOMElement.h"
#endif
#ifdef NS_DEBUG
static PRBool gNoisy = PR_FALSE;
#else
static const PRBool gNoisy = PR_FALSE;
#endif
DeleteElementTxn::DeleteElementTxn()
: EditTxn()
{
}
NS_IMETHODIMP DeleteElementTxn::Init(nsIDOMNode *aElement)
{
if (nsnull!=aElement) {
mElement = do_QueryInterface(aElement);
}
else
return NS_ERROR_NULL_POINTER;
return NS_OK;
}
DeleteElementTxn::~DeleteElementTxn()
{
}
NS_IMETHODIMP DeleteElementTxn::Do(void)
{
if (gNoisy) { printf("%p Do Delete Element element = %p\n", this, mElement.get()); }
if (!mElement)
return NS_ERROR_NULL_POINTER;
nsresult result = mElement->GetParentNode(getter_AddRefs(mParent));
if (NS_FAILED(result)) {
return result;
}
if (!mParent) {
return NS_OK; // this is a no-op, there's no parent to delete mElement from
}
#ifdef NS_DEBUG
// begin debug output
nsCOMPtr<nsIDOMElement> element;
element = do_QueryInterface(mElement);
nsAutoString elementTag="text node";
if (element)
element->GetTagName(elementTag);
nsCOMPtr<nsIDOMElement> parentElement;
parentElement = do_QueryInterface(mParent);
nsAutoString parentElementTag="text node";
if (parentElement)
parentElement->GetTagName(parentElementTag);
char *c, *p;
c = elementTag.ToNewCString();
p = parentElementTag.ToNewCString();
if (c&&p)
{
if (gNoisy)
printf(" DeleteElementTxn: deleting child %s from parent %s\n", c, p);
delete [] c;
delete [] p;
}
// end debug output
#endif
// remember which child mElement was (by remembering which child was next)
result = mElement->GetNextSibling(getter_AddRefs(mRefNode)); // can return null mRefNode
nsCOMPtr<nsIDOMNode> resultNode;
result = mParent->RemoveChild(mElement, getter_AddRefs(resultNode));
return result;
}
NS_IMETHODIMP DeleteElementTxn::Undo(void)
{
if (gNoisy) { printf("%p Undo Delete Element element = %p, parent = %p\n", this, mElement.get(), mParent.get()); }
if (!mParent) { return NS_OK; } // this is a legal state, the txn is a no-op
if (!mElement) { return NS_ERROR_NULL_POINTER; }
#ifdef NS_DEBUG
// begin debug output
nsCOMPtr<nsIDOMElement> element;
element = do_QueryInterface(mElement);
nsAutoString elementTag="text node";
if (element)
element->GetTagName(elementTag);
nsCOMPtr<nsIDOMElement> parentElement;
parentElement = do_QueryInterface(mParent);
nsAutoString parentElementTag="text node";
if (parentElement)
parentElement->GetTagName(parentElementTag);
char *c, *p;
c = elementTag.ToNewCString();
p = parentElementTag.ToNewCString();
if (c&&p)
{
if (gNoisy)
printf(" DeleteElementTxn: inserting child %s back into parent %s\n", c, p);
delete [] c;
delete [] p;
}
// end debug output
#endif
nsCOMPtr<nsIDOMNode> resultNode;
nsresult result = mParent->InsertBefore(mElement, mRefNode, getter_AddRefs(resultNode));
return result;
}
NS_IMETHODIMP DeleteElementTxn::Redo(void)
{
if (gNoisy) { printf("%p Redo Delete Element element = %p, parent = %p\n", this, mElement.get(), mParent.get()); }
if (!mParent) { return NS_OK; } // this is a legal state, the txn is a no-op
if (!mElement) { return NS_ERROR_NULL_POINTER; }
nsCOMPtr<nsIDOMNode> resultNode;
nsresult result = mParent->RemoveChild(mElement, getter_AddRefs(resultNode));
return result;
}
NS_IMETHODIMP DeleteElementTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
if (nsnull!=aDidMerge)
*aDidMerge=PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP DeleteElementTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP DeleteElementTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Insert Element: ";
}
return NS_OK;
}
NS_IMETHODIMP DeleteElementTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Remove Element: ";
}
return NS_OK;
}

View File

@@ -0,0 +1,84 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef DeleteElementTxn_h__
#define DeleteElementTxn_h__
#include "EditTxn.h"
#include "nsIDOMNode.h"
#include "nsCOMPtr.h"
#define DELETE_ELEMENT_TXN_CID \
{/* 6fd77770-ac49-11d2-86d8-000064657374 */ \
0x6fd77770, 0xac49, 0x11d2, \
{0x86, 0xd8, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74} }
/**
* A transaction that deletes a single element
*/
class DeleteElementTxn : public EditTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = DELETE_ELEMENT_TXN_CID; return iid; }
/** initialize the transaction.
* @param aElement the node to delete
*/
NS_IMETHOD Init(nsIDOMNode *aElement);
private:
DeleteElementTxn();
public:
virtual ~DeleteElementTxn();
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Redo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
protected:
/** the element to delete */
nsCOMPtr<nsIDOMNode> mElement;
/** the node into which the new node will be inserted */
nsCOMPtr<nsIDOMNode> mParent;
/** the index in mParent for the new node */
PRUint32 mOffsetInParent;
/** the node we will insert mNewNode before. We compute this ourselves. */
nsCOMPtr<nsIDOMNode> mRefNode;
friend class TransactionFactory;
};
#endif

View File

@@ -0,0 +1,363 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "DeleteRangeTxn.h"
#include "nsIDOMRange.h"
#include "nsIDOMCharacterData.h"
#include "nsIDOMNodeList.h"
#include "nsIDOMSelection.h"
#include "DeleteTextTxn.h"
#include "DeleteElementTxn.h"
#include "TransactionFactory.h"
#include "nsIContentIterator.h"
#include "nsIContent.h"
#include "nsLayoutCID.h"
#ifdef NS_DEBUG
#include "nsIDOMElement.h"
#endif
#ifdef NS_DEBUG
static PRBool gNoisy = PR_FALSE;
#else
static const PRBool gNoisy = PR_FALSE;
#endif
// note that aEditor is not refcounted
DeleteRangeTxn::DeleteRangeTxn()
: EditAggregateTxn()
{
}
NS_IMETHODIMP DeleteRangeTxn::Init(nsIEditor *aEditor, nsIDOMRange *aRange)
{
if (aEditor && aRange)
{
mEditor = aEditor;
mRange = do_QueryInterface(aRange);
nsresult result = aRange->GetStartParent(getter_AddRefs(mStartParent));
NS_ASSERTION((NS_SUCCEEDED(result)), "GetStartParent failed.");
result = aRange->GetEndParent(getter_AddRefs(mEndParent));
NS_ASSERTION((NS_SUCCEEDED(result)), "GetEndParent failed.");
result = aRange->GetStartOffset(&mStartOffset);
NS_ASSERTION((NS_SUCCEEDED(result)), "GetStartOffset failed.");
result = aRange->GetEndOffset(&mEndOffset);
NS_ASSERTION((NS_SUCCEEDED(result)), "GetEndOffset failed.");
result = aRange->GetCommonParent(getter_AddRefs(mCommonParent));
NS_ASSERTION((NS_SUCCEEDED(result)), "GetCommonParent failed.");
#ifdef NS_DEBUG
{
PRUint32 count;
nsCOMPtr<nsIDOMCharacterData> textNode;
textNode = do_QueryInterface(mStartParent);
if (textNode)
textNode->GetLength(&count);
else
{
nsCOMPtr<nsIDOMNodeList> children;
result = mStartParent->GetChildNodes(getter_AddRefs(children));
NS_ASSERTION(((NS_SUCCEEDED(result)) && children), "bad start child list");
children->GetLength(&count);
}
NS_ASSERTION(mStartOffset<=(PRInt32)count, "bad start offset");
textNode = do_QueryInterface(mEndParent);
if (textNode)
textNode->GetLength(&count);
else
{
nsCOMPtr<nsIDOMNodeList> children;
result = mEndParent->GetChildNodes(getter_AddRefs(children));
NS_ASSERTION(((NS_SUCCEEDED(result)) && children), "bad end child list");
children->GetLength(&count);
}
NS_ASSERTION(mEndOffset<=(PRInt32)count, "bad end offset");
if (gNoisy)
{
printf ("DeleteRange: %d of %p to %d of %p\n",
mStartOffset, (void *)mStartParent, mEndOffset, (void *)mEndParent);
}
}
#endif
return result;
}
else
return NS_ERROR_NULL_POINTER;
}
DeleteRangeTxn::~DeleteRangeTxn()
{
}
NS_IMETHODIMP DeleteRangeTxn::Do(void)
{
if (gNoisy) { printf("Do Delete Range\n"); }
if (!mStartParent || !mEndParent || !mCommonParent)
return NS_ERROR_NULL_POINTER;
nsresult result;
// build the child transactions
if (mStartParent==mEndParent)
{ // the selection begins and ends in the same node
result = CreateTxnsToDeleteBetween(mStartParent, mStartOffset, mEndOffset);
}
else
{ // the selection ends in a different node from where it started
// delete the relevant content in the start node
result = CreateTxnsToDeleteContent(mStartParent, mStartOffset, nsIEditor::eDeleteNext);
if (NS_SUCCEEDED(result))
{
// delete the intervening nodes
result = CreateTxnsToDeleteNodesBetween();
if (NS_SUCCEEDED(result))
{
// delete the relevant content in the end node
result = CreateTxnsToDeleteContent(mEndParent, mEndOffset, nsIEditor::eDeletePrevious);
}
}
}
// if we've successfully built this aggregate transaction, then do it.
if (NS_SUCCEEDED(result)) {
result = EditAggregateTxn::Do();
}
if (NS_SUCCEEDED(result)) {
// set the resulting selection
nsCOMPtr<nsIDOMSelection> selection;
result = mEditor->GetSelection(getter_AddRefs(selection));
if (NS_SUCCEEDED(result)) {
result = selection->Collapse(mStartParent, mStartOffset);
}
}
return result;
}
NS_IMETHODIMP DeleteRangeTxn::Undo(void)
{
if (gNoisy) { printf("Undo Delete Range\n"); }
if (!mStartParent || !mEndParent || !mCommonParent)
return NS_ERROR_NULL_POINTER;
nsresult result = EditAggregateTxn::Undo();
if (NS_SUCCEEDED(result)) {
// set the resulting selection
nsCOMPtr<nsIDOMSelection> selection;
result = mEditor->GetSelection(getter_AddRefs(selection));
if (NS_SUCCEEDED(result)) {
selection->Collapse(mStartParent, mStartOffset);
selection->Extend(mEndParent, mEndOffset);
}
}
return result;
}
NS_IMETHODIMP DeleteRangeTxn::Redo(void)
{
if (gNoisy) { printf("Redo Delete Range\n"); }
if (!mStartParent || !mEndParent || !mCommonParent)
return NS_ERROR_NULL_POINTER;
nsresult result = EditAggregateTxn::Redo();
if (NS_SUCCEEDED(result)) {
// set the resulting selection
nsCOMPtr<nsIDOMSelection> selection;
result = mEditor->GetSelection(getter_AddRefs(selection));
if (NS_SUCCEEDED(result)) {
result = selection->Collapse(mStartParent, mStartOffset);
}
}
return result;
}
NS_IMETHODIMP DeleteRangeTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
if (nsnull!=aDidMerge)
*aDidMerge=PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP DeleteRangeTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP DeleteRangeTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Insert Range: ";
}
return NS_OK;
}
NS_IMETHODIMP DeleteRangeTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Remove Range: ";
}
return NS_OK;
}
NS_IMETHODIMP DeleteRangeTxn::CreateTxnsToDeleteBetween(nsIDOMNode *aStartParent,
PRUint32 aStartOffset,
PRUint32 aEndOffset)
{
nsresult result;
// see what kind of node we have
nsCOMPtr<nsIDOMCharacterData> textNode;
textNode = do_QueryInterface(aStartParent);
if (textNode)
{ // if the node is a text node, then delete text content
DeleteTextTxn *txn;
result = TransactionFactory::GetNewTransaction(DeleteTextTxn::GetCID(), (EditTxn **)&txn);
if (nsnull!=txn)
{
PRInt32 numToDel;
if (aStartOffset==aEndOffset)
numToDel = 1;
else
numToDel = aEndOffset-aStartOffset;
txn->Init(mEditor, textNode, aStartOffset, numToDel);
AppendChild(txn);
}
}
else
{
PRUint32 childCount;
nsCOMPtr<nsIDOMNodeList> children;
result = aStartParent->GetChildNodes(getter_AddRefs(children));
if ((NS_SUCCEEDED(result)) && children)
{
children->GetLength(&childCount);
NS_ASSERTION(aEndOffset<=childCount, "bad aEndOffset");
PRUint32 i;
for (i=aStartOffset; i<=aEndOffset; i++)
{
nsCOMPtr<nsIDOMNode> child;
result = children->Item(i, getter_AddRefs(child));
if ((NS_SUCCEEDED(result)) && child)
{
DeleteElementTxn *txn;
result = TransactionFactory::GetNewTransaction(DeleteElementTxn::GetCID(), (EditTxn **)&txn);
if (nsnull!=txn)
{
txn->Init(child);
AppendChild(txn);
}
else
return NS_ERROR_NULL_POINTER;
}
}
}
}
return result;
}
NS_IMETHODIMP DeleteRangeTxn::CreateTxnsToDeleteContent(nsIDOMNode *aParent,
PRUint32 aOffset,
nsIEditor::ESelectionCollapseDirection aAction)
{
nsresult result;
// see what kind of node we have
nsCOMPtr<nsIDOMCharacterData> textNode;
textNode = do_QueryInterface(aParent);
if (textNode)
{ // if the node is a text node, then delete text content
PRUint32 start, numToDelete;
if (nsIEditor::eDeleteNext == aAction)
{
start=aOffset;
textNode->GetLength(&numToDelete);
numToDelete -= aOffset;
}
else
{
start=0;
numToDelete=aOffset;
}
if (numToDelete)
{
DeleteTextTxn *txn;
result = TransactionFactory::GetNewTransaction(DeleteTextTxn::GetCID(), (EditTxn **)&txn);
if (nsnull!=txn)
{
txn->Init(mEditor, textNode, start, numToDelete);
AppendChild(txn);
}
else
return NS_ERROR_NULL_POINTER;
}
}
return result;
}
static NS_DEFINE_IID(kSubtreeIteratorCID, NS_SUBTREEITERATOR_CID);
static NS_DEFINE_IID(kRangeCID, NS_RANGE_CID);
NS_IMETHODIMP DeleteRangeTxn::CreateTxnsToDeleteNodesBetween()
{
nsresult result;
nsCOMPtr<nsIContentIterator> iter;
result = nsComponentManager::CreateInstance(kSubtreeIteratorCID,
nsnull,
nsIContentIterator::GetIID(),
getter_AddRefs(iter));
if (!NS_SUCCEEDED(result))
return result;
result = iter->Init(mRange);
if (!NS_SUCCEEDED(result))
return result;
while (NS_COMFALSE == iter->IsDone())
{
nsCOMPtr<nsIDOMNode> node;
nsCOMPtr<nsIContent> content;
result = iter->CurrentNode(getter_AddRefs(content));
node = do_QueryInterface(content);
if ((NS_SUCCEEDED(result)) && node)
{
DeleteElementTxn *txn;
result = TransactionFactory::GetNewTransaction(DeleteElementTxn::GetCID(), (EditTxn **)&txn);
if (nsnull!=txn)
{
txn->Init(node);
AppendChild(txn);
}
else
return NS_ERROR_NULL_POINTER;
}
iter->Next();
}
return result;
}

View File

@@ -0,0 +1,113 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef DeleteRangeTxn_h__
#define DeleteRangeTxn_h__
#include "EditAggregateTxn.h"
#include "nsIDOMNode.h"
#include "nsIDOMRange.h"
#include "nsIEditor.h"
#include "nsCOMPtr.h"
class nsIDOMDocument;
#define DELETE_RANGE_TXN_CID \
{/* 5ec6b260-ac49-11d2-86d8-000064657374 */ \
0x5ec6b260, 0xac49, 0x11d2, \
{0x86, 0xd8, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74} }
class nsIDOMRange;
class nsIEditor;
/**
* A transaction that deletes an entire range in the content tree
*/
class DeleteRangeTxn : public EditAggregateTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = DELETE_RANGE_TXN_CID; return iid; }
/** initialize the transaction.
* @param aEditor the object providing basic editing operations
* @param aRange the range to delete
*/
NS_IMETHOD Init(nsIEditor *aEditor, nsIDOMRange *aRange);
private:
DeleteRangeTxn();
public:
virtual ~DeleteRangeTxn();
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Redo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
protected:
NS_IMETHOD CreateTxnsToDeleteBetween(nsIDOMNode *aStartParent,
PRUint32 aStartOffset,
PRUint32 aEndOffset);
NS_IMETHOD CreateTxnsToDeleteNodesBetween();
NS_IMETHOD CreateTxnsToDeleteContent(nsIDOMNode *aParent,
PRUint32 aOffset,
nsIEditor::ESelectionCollapseDirection aAction);
protected:
/** p1 in the range */
nsCOMPtr<nsIDOMRange> mRange; // is this really an owning ptr?
/** p1 in the range */
nsCOMPtr<nsIDOMNode> mStartParent;
/** p1 offset */
PRInt32 mStartOffset;
/** p2 in the range */
nsCOMPtr<nsIDOMNode> mEndParent;
/** the closest common parent of p1 and p2 */
nsCOMPtr<nsIDOMNode> mCommonParent;
/** p2 offset */
PRInt32 mEndOffset;
/** the editor for this transaction */
nsIEditor* mEditor;
friend class TransactionFactory;
};
#endif

View File

@@ -0,0 +1,132 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "DeleteTextTxn.h"
#include "nsIDOMCharacterData.h"
#include "nsIDOMSelection.h"
#ifdef NS_DEBUG
static PRBool gNoisy = PR_FALSE;
#else
static const PRBool gNoisy = PR_FALSE;
#endif
DeleteTextTxn::DeleteTextTxn()
: EditTxn()
{
}
DeleteTextTxn::~DeleteTextTxn()
{
}
NS_IMETHODIMP DeleteTextTxn::Init(nsIEditor *aEditor,
nsIDOMCharacterData *aElement,
PRUint32 aOffset,
PRUint32 aNumCharsToDelete)
{
NS_ASSERTION(aEditor&&aElement, "bad arg");
mEditor = aEditor;
mElement = do_QueryInterface(aElement);
mOffset = aOffset;
mNumCharsToDelete = aNumCharsToDelete;
NS_ASSERTION(0!=aNumCharsToDelete, "bad arg, numCharsToDelete");
PRUint32 count;
aElement->GetLength(&count);
NS_ASSERTION(count>=aNumCharsToDelete, "bad arg, numCharsToDelete. Not enough characters in node");
NS_ASSERTION(count>=aOffset+aNumCharsToDelete, "bad arg, numCharsToDelete. Not enough characters in node");
mDeletedText = "";
return NS_OK;
}
NS_IMETHODIMP DeleteTextTxn::Do(void)
{
if (gNoisy) { printf("Do Delete Text\n"); }
nsresult result = NS_ERROR_NULL_POINTER;
if (mEditor && mElement)
{
// get the text that we're about to delete
result = mElement->SubstringData(mOffset, mNumCharsToDelete, mDeletedText);
NS_ASSERTION(NS_SUCCEEDED(result), "could not get text to delete.");
result = mElement->DeleteData(mOffset, mNumCharsToDelete);
if (NS_SUCCEEDED(result))
{
nsCOMPtr<nsIDOMSelection> selection;
nsresult selectionResult = mEditor->GetSelection(getter_AddRefs(selection));
if (NS_SUCCEEDED(selectionResult) && selection) {
selectionResult = selection->Collapse(mElement, mOffset);
NS_ASSERTION((NS_SUCCEEDED(selectionResult)), "selection could not be collapsed after undo of insert.");
}
}
}
return result;
}
//XXX: we may want to store the selection state and restore it properly
// was it an insertion point or an extended selection?
NS_IMETHODIMP DeleteTextTxn::Undo(void)
{
if (gNoisy) { printf("Undo Delete Text\n"); }
nsresult result = NS_ERROR_NULL_POINTER;
if (mEditor && mElement)
{
result = mElement->InsertData(mOffset, mDeletedText);
if (NS_SUCCEEDED(result))
{
nsCOMPtr<nsIDOMSelection> selection;
nsresult selectionResult = mEditor->GetSelection(getter_AddRefs(selection));
if (NS_SUCCEEDED(selectionResult) && selection) {
selectionResult = selection->Collapse(mElement, mOffset);
NS_ASSERTION((NS_SUCCEEDED(selectionResult)), "selection could not be collapsed after undo of insert.");
}
}
}
return result;
}
NS_IMETHODIMP DeleteTextTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
if (nsnull!=aDidMerge)
*aDidMerge=PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP DeleteTextTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP DeleteTextTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Insert Text: ";
*aString += mDeletedText;
}
return NS_OK;
}
NS_IMETHODIMP DeleteTextTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Remove Text: ";
*aString += mDeletedText;
}
return NS_OK;
}

View File

@@ -0,0 +1,91 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef DeleteTextTxn_h__
#define DeleteTextTxn_h__
#include "EditTxn.h"
#include "nsIEditor.h"
#include "nsIDOMCharacterData.h"
#include "nsCOMPtr.h"
#define DELETE_TEXT_TXN_CID \
{/* 4d3a2720-ac49-11d2-86d8-000064657374 */ \
0x4d3a2720, 0xac49, 0x11d2, \
{0x86, 0xd8, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74} }
/**
* A transaction that removes text from a content node.
*/
class DeleteTextTxn : public EditTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = DELETE_TEXT_TXN_CID; return iid; }
/** initialize the transaction.
* @param aEditor the provider of basic editing operations
* @param aElement the content node to remove text from
* @param aOffset the location in aElement to begin the deletion
* @param aNumCharsToDelete the number of characters to delete. Not the number of bytes!
*/
NS_IMETHOD Init(nsIEditor *aEditor,
nsIDOMCharacterData *aElement,
PRUint32 aOffset,
PRUint32 aNumCharsToDelete);
private:
DeleteTextTxn();
public:
virtual ~DeleteTextTxn();
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
protected:
/** the provider of basic editing operations */
nsIEditor* mEditor;
/** the text element to operate upon */
nsCOMPtr<nsIDOMCharacterData> mElement;
/** the offset into mElement where the deletion is to take place */
PRUint32 mOffset;
/** the number of characters to delete */
PRUint32 mNumCharsToDelete;
/** the text that was deleted */
nsString mDeletedText;
friend class TransactionFactory;
};
#endif

View File

@@ -0,0 +1,236 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL") you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "EditAggregateTxn.h"
#include "nsCOMPtr.h"
#include "nsIDOMNode.h"
#include "nsVoidArray.h"
EditAggregateTxn::EditAggregateTxn()
: EditTxn()
{
// base class does this: NS_INIT_REFCNT();
mChildren = new nsVoidArray();
}
EditAggregateTxn::~EditAggregateTxn()
{
if (nsnull!=mChildren)
{
PRInt32 i;
PRInt32 count = mChildren->Count();
for (i=0; i<count; i++)
{
EditTxn *txn = (EditTxn*)(mChildren->ElementAt(i));
NS_IF_RELEASE(txn);
}
delete mChildren;
}
}
NS_IMETHODIMP EditAggregateTxn::Do(void)
{
nsresult result=NS_OK; // it's legal (but not very useful) to have an empty child list
if (nsnull!=mChildren)
{
PRInt32 i;
PRInt32 count = mChildren->Count();
for (i=0; i<count; i++)
{
EditTxn *txn = (EditTxn*)(mChildren->ElementAt(i));
result = txn->Do();
if (NS_FAILED(result))
break;
}
}
return result;
}
NS_IMETHODIMP EditAggregateTxn::Undo(void)
{
nsresult result=NS_OK; // it's legal (but not very useful) to have an empty child list
if (nsnull!=mChildren)
{
PRInt32 i;
PRInt32 count = mChildren->Count();
// undo goes through children backwards
for (i=count-1; i>=0; i--)
{
EditTxn *txn = (EditTxn*)(mChildren->ElementAt(i));
result = txn->Undo();
if (NS_FAILED(result))
break;
}
}
return result;
}
NS_IMETHODIMP EditAggregateTxn::Redo(void)
{
nsresult result=NS_OK; // it's legal (but not very useful) to have an empty child list
if (nsnull!=mChildren)
{
PRInt32 i;
PRInt32 count = mChildren->Count();
for (i=0; i<count; i++)
{
EditTxn *txn = (EditTxn*)(mChildren->ElementAt(i));
result = txn->Redo();
if (NS_FAILED(result))
break;
}
}
return result;
}
NS_IMETHODIMP EditAggregateTxn::GetIsTransient(PRBool *aIsTransient)
{
if (nsnull!=aIsTransient)
*aIsTransient = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP EditAggregateTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
nsresult result=NS_OK; // it's legal (but not very useful) to have an empty child list
if (nsnull!=aDidMerge)
*aDidMerge=PR_FALSE;
if (nsnull!=mChildren)
{
PRInt32 count = mChildren->Count();
NS_ASSERTION(count>0, "bad count");
if (0<count)
{
EditTxn *txn = (EditTxn*)(mChildren->ElementAt(count-1));
result = txn->Merge(aDidMerge, aTransaction);
}
}
return result;
}
NS_IMETHODIMP EditAggregateTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP EditAggregateTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
*aString="";
return NS_OK;
}
NS_IMETHODIMP EditAggregateTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
*aString="";
return NS_OK;
}
NS_IMETHODIMP EditAggregateTxn::AppendChild(EditTxn *aTxn)
{
if ((nsnull!=mChildren) && (nsnull!=aTxn))
{
mChildren->AppendElement(aTxn);
return NS_OK;
}
return NS_ERROR_NULL_POINTER;
}
NS_IMETHODIMP EditAggregateTxn::GetCount(PRInt32 *aCount)
{
if (!aCount) {
return NS_ERROR_NULL_POINTER;
}
*aCount=0;
if (mChildren) {
*aCount = mChildren->Count();
}
return NS_OK;
}
NS_IMETHODIMP EditAggregateTxn::GetTxnAt(PRInt32 aIndex, EditTxn **aTxn)
{
if (!aTxn) {
return NS_ERROR_NULL_POINTER;
}
if (!mChildren) {
return NS_ERROR_UNEXPECTED;
}
const PRInt32 txnCount = mChildren->Count();
if (0>aIndex || txnCount<=aIndex) {
return NS_ERROR_UNEXPECTED;
}
*aTxn = (EditTxn *)(mChildren->ElementAt(aIndex));
if (!*aTxn)
return NS_ERROR_UNEXPECTED;
NS_ADDREF(*aTxn);
return NS_OK;
}
NS_IMETHODIMP EditAggregateTxn::SetName(nsIAtom *aName)
{
mName = do_QueryInterface(aName);
return NS_OK;
}
NS_IMETHODIMP EditAggregateTxn::GetName(nsIAtom **aName)
{
if (aName)
{
if (mName)
{
*aName = mName;
NS_ADDREF(*aName);
return NS_OK;
}
}
return NS_ERROR_NULL_POINTER;
}
NS_IMETHODIMP_(nsrefcnt) EditAggregateTxn::AddRef(void)
{
return EditTxn::AddRef();
}
//NS_IMPL_RELEASE_INHERITED(Class, Super)
NS_IMETHODIMP_(nsrefcnt) EditAggregateTxn::Release(void)
{
return EditTxn::Release();
}
//NS_IMPL_QUERY_INTERFACE_INHERITED(Class, Super, AdditionalInterface)
NS_IMETHODIMP EditAggregateTxn::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (!aInstancePtr) return NS_ERROR_NULL_POINTER;
if (aIID.Equals(EditAggregateTxn::GetCID())) {
*aInstancePtr = (nsISupports*)(EditAggregateTxn*)(this);
NS_ADDREF_THIS();
return NS_OK;
}
return EditTxn::QueryInterface(aIID, aInstancePtr);
}

View File

@@ -0,0 +1,91 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef EditAggregateTxn_h__
#define EditAggregateTxn_h__
#include "EditTxn.h"
#include "nsIAtom.h"
#include "nsCOMPtr.h"
#define EDIT_AGGREGATE_TXN_CID \
{/* 345921a0-ac49-11d2-86d8-000064657374 */ \
0x345921a0, 0xac49, 0x11d2, \
{0x86, 0xd8, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74} }
class nsVoidArray;
/**
* base class for all document editing transactions that require aggregation.
* provides a list of child transactions.
*/
class EditAggregateTxn : public EditTxn
{
public:
NS_DECL_ISUPPORTS_INHERITED
static const nsIID& GetCID() { static nsIID cid = EDIT_AGGREGATE_TXN_CID; return cid; }
EditAggregateTxn();
virtual ~EditAggregateTxn();
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Redo(void);
NS_IMETHOD GetIsTransient(PRBool *aIsTransient);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
/** append a transaction to this aggregate */
NS_IMETHOD AppendChild(EditTxn *aTxn);
/** get the number of nested txns.
* This is the number of top-level txns, it does not do recursive decent.
*/
NS_IMETHOD GetCount(PRInt32 *aCount);
/** get the txn at index aIndex.
* returns NS_ERROR_UNEXPECTED if there is no txn at aIndex.
*/
NS_IMETHOD GetTxnAt(PRInt32 aIndex, EditTxn **aTxn);
/** set the name assigned to this txn */
NS_IMETHOD SetName(nsIAtom *aName);
/** get the name assigned to this txn */
NS_IMETHOD GetName(nsIAtom **aName);
protected:
//XXX: if this was an nsISupportsArray, it would handle refcounting for us
nsVoidArray * mChildren;
nsCOMPtr<nsIAtom> mName;
};
#endif

View File

@@ -0,0 +1,404 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsIDOMDocument.h"
#include "nsEditor.h"
#include "nsIDOMText.h"
#include "nsIDOMElement.h"
#include "nsIDOMAttr.h"
#include "nsIDOMNode.h"
#include "nsIDOMNodeList.h"
#include "nsIDOMRange.h"
#include "nsIDOMSelection.h"
#include "nsIAtom.h"
#include "nsIDOMHTMLTableElement.h"
#include "nsIDOMHTMLTableCellElement.h"
#include "nsITableCellLayout.h" // For efficient access to table cell
#include "nsITableLayout.h" // data owned by the table and cell frames
// transactions the editor knows how to build
//#include "TransactionFactory.h"
//#include "EditAggregateTxn.h"
//#include "nsIDOMHTMLCollection.h"
#include "nsHTMLEditor.h"
// Table Editing methods
NS_IMETHODIMP
nsHTMLEditor::InsertTable()
{
nsresult res=NS_ERROR_NOT_INITIALIZED;
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsHTMLEditor::InsertTableCell(PRInt32 aNumber, PRBool aAfter)
{
nsCOMPtr<nsIDOMSelection> selection;
nsCOMPtr<nsIDOMElement> table;
nsCOMPtr<nsIDOMElement> cell;
nsCOMPtr<nsIDOMNode> cellParent;
PRInt32 cellOffset, startRow, startCol;
nsresult res = GetCellContext(selection, table, cell, cellParent, cellOffset, startRow, startCol);
if (NS_SUCCEEDED(res))
{
PRInt32 i;
for (i = 0; i < aNumber; i++)
{
nsCOMPtr<nsIDOMElement> newCell;
res = CreateElementWithDefaults("td", getter_AddRefs(newCell));
if (NS_SUCCEEDED(res) && newCell)
{
if (aAfter) cellOffset++;
res = InsertNode(newCell, cellParent, cellOffset);
}
}
SetCaretAfterTableEdit(table, startRow, startCol, ePreviousColumn);
}
return res;
}
NS_IMETHODIMP
nsHTMLEditor::InsertTableColumn(PRInt32 aNumber, PRBool aAfter)
{
nsCOMPtr<nsIDOMSelection> selection;
nsCOMPtr<nsIDOMElement> table;
nsCOMPtr<nsIDOMElement> cell;
nsCOMPtr<nsIDOMNode> cellParent;
PRInt32 cellOffset, startRow, startCol;
nsresult res = GetCellContext(selection, table, cell, cellParent, cellOffset, startRow, startCol);
if (NS_SUCCEEDED(res))
{
PRInt32 rowCount, colCount, row, col;
if (NS_FAILED(GetTableSize(table, rowCount, colCount)))
return NS_ERROR_FAILURE;
for ( row = 0; row < rowCount; row++)
{
nsCOMPtr<nsIDOMElement> curCell;
PRInt32 startRow, startCol, rowSpan, colSpan;
PRBool isSelected;
res = GetCellDataAt(table, row, col, *getter_AddRefs(curCell),
startRow, startCol, rowSpan, colSpan, isSelected);
if (NS_SUCCEEDED(res) && curCell)
{
//FINISH ME!
}
}
}
return res;
}
NS_IMETHODIMP
nsHTMLEditor::InsertTableRow(PRInt32 aNumber, PRBool aAfter)
{
nsCOMPtr<nsIDOMSelection> selection;
nsCOMPtr<nsIDOMElement> table;
nsCOMPtr<nsIDOMElement> cell;
nsCOMPtr<nsIDOMNode> cellParent;
PRInt32 cellOffset, startRow, startCol;
nsresult res = GetCellContext(selection, table, cell, cellParent, cellOffset, startRow, startCol);
if (NS_SUCCEEDED(res))
{
selection->ClearSelection();
}
return res;
}
NS_IMETHODIMP
nsHTMLEditor::DeleteTable()
{
nsCOMPtr<nsIDOMSelection> selection;
nsCOMPtr<nsIDOMElement> table;
nsCOMPtr<nsIDOMElement> cell;
nsCOMPtr<nsIDOMNode> cellParent;
PRInt32 cellOffset, startRow, startCol;
nsresult res = GetCellContext(selection, table, cell, cellParent, cellOffset, startRow, startCol);
if (NS_SUCCEEDED(res))
{
// Save where we need to restore the selection
nsCOMPtr<nsIDOMNode> tableParent;
PRInt32 tableOffset;
if(NS_FAILED(table->GetParentNode(getter_AddRefs(tableParent))) || !tableParent)
return NS_ERROR_FAILURE;
res = DeleteNode(table);
// Restore the selection (caret)
nsCOMPtr<nsIDOMSelection>selection;
res = nsEditor::GetSelection(getter_AddRefs(selection));
if (NS_FAILED(res) || !selection)
return res;
selection->Collapse(tableParent, tableOffset);
}
return res;
}
NS_IMETHODIMP
nsHTMLEditor::DeleteTableCell(PRInt32 aNumber)
{
nsCOMPtr<nsIDOMSelection> selection;
nsCOMPtr<nsIDOMElement> table;
nsCOMPtr<nsIDOMElement> cell;
nsCOMPtr<nsIDOMNode> cellParent;
PRInt32 cellOffset, startRow, startCol;
nsresult res = GetCellContext(selection, table, cell, cellParent, cellOffset, startRow, startCol);
if (NS_SUCCEEDED(res))
{
selection->ClearSelection();
PRInt32 i;
for (i = 0; i < aNumber; i++)
{
//TODO: FINISH ME!
if (NS_FAILED(DeleteNode(cell)))
break;
}
SetCaretAfterTableEdit(table, startRow, startCol, ePreviousColumn);
}
return res;
}
NS_IMETHODIMP
nsHTMLEditor::DeleteTableColumn(PRInt32 aNumber)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsHTMLEditor::DeleteTableRow(PRInt32 aNumber)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsHTMLEditor::JoinTableCells(PRBool aCellToRight)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsHTMLEditor::NormalizeTable(nsIDOMElement *aTable)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsHTMLEditor::GetCellIndexes(nsIDOMElement *aCell, PRInt32 &aColIndex, PRInt32 &aRowIndex)
{
nsresult res=NS_ERROR_NOT_INITIALIZED;
aColIndex=0; // initialize out params
aRowIndex=0;
if (!aCell)
{
// Get the selected cell or the cell enclosing the selection anchor
nsCOMPtr<nsIDOMElement> cell;
res = GetElementOrParentByTagName("td", nsnull, getter_AddRefs(cell));
if (NS_SUCCEEDED(res) && cell)
aCell = cell;
else
return NS_ERROR_FAILURE;
}
res = NS_ERROR_FAILURE; // we return an error unless we get the index
nsISupports *layoutObject=nsnull; // frames are not ref counted, so don't use an nsCOMPtr
res = nsHTMLEditor::GetLayoutObject(aCell, &layoutObject);
if ((NS_SUCCEEDED(res)) && (nsnull!=layoutObject))
{ // get the table cell interface from the frame
nsITableCellLayout *cellLayoutObject=nsnull; // again, frames are not ref-counted
res = layoutObject->QueryInterface(nsITableCellLayout::GetIID(), (void**)(&cellLayoutObject));
if ((NS_SUCCEEDED(res)) && (nsnull!=cellLayoutObject))
{
res = cellLayoutObject->GetCellIndexes(aRowIndex, aColIndex);
}
}
return res;
}
NS_IMETHODIMP
nsHTMLEditor::GetTableLayoutObject(nsIDOMElement* aTable, nsITableLayout **tableLayoutObject)
{
*tableLayoutObject=nsnull;
if (!aTable)
return NS_ERROR_NOT_INITIALIZED;
// frames are not ref counted, so don't use an nsCOMPtr
nsISupports *layoutObject=nsnull;
nsresult res = nsHTMLEditor::GetLayoutObject(aTable, &layoutObject);
if ((NS_SUCCEEDED(res)) && (nsnull!=layoutObject))
{ // get the table interface from the frame
res = layoutObject->QueryInterface(nsITableLayout::GetIID(),
(void**)(tableLayoutObject));
}
return res;
}
/* Not scriptable: For convenience in C++ */
NS_IMETHODIMP
nsHTMLEditor::GetTableSize(nsIDOMElement *aTable, PRInt32& aRowCount, PRInt32& aColCount)
{
nsresult res=NS_ERROR_FAILURE;
aRowCount = 0;
aColCount = 0;
if (!aTable)
{
// Get the selected talbe or the table enclosing the selection anchor
nsCOMPtr<nsIDOMElement> table;
res = GetElementOrParentByTagName("table", nsnull, getter_AddRefs(table));
if (NS_SUCCEEDED(res) && table)
aTable = table;
else
return NS_ERROR_FAILURE;
}
// frames are not ref counted, so don't use an nsCOMPtr
nsITableLayout *tableLayoutObject;
res = GetTableLayoutObject(aTable, &tableLayoutObject);
if ((NS_SUCCEEDED(res)) && (nsnull!=tableLayoutObject))
{
res = tableLayoutObject->GetTableSize(aRowCount, aColCount);
}
return res;
}
NS_IMETHODIMP
nsHTMLEditor::GetCellDataAt(nsIDOMElement* aTable, PRInt32 aRowIndex, PRInt32 aColIndex, nsIDOMElement* &aCell,
PRInt32& aStartRowIndex, PRInt32& aStartColIndex,
PRInt32& aRowSpan, PRInt32& aColSpan, PRBool& aIsSelected)
{
nsresult res=NS_ERROR_FAILURE;
aCell = nsnull;
aStartRowIndex = 0;
aStartColIndex = 0;
aRowSpan = 0;
aColSpan = 0;
aIsSelected = PR_FALSE;
if (!aTable)
{
// Get the selected talbe or the table enclosing the selection anchor
nsCOMPtr<nsIDOMElement> table;
res = GetElementOrParentByTagName("table", nsnull, getter_AddRefs(table));
if (NS_SUCCEEDED(res) && table)
aTable = table;
else
return NS_ERROR_FAILURE;
}
// frames are not ref counted, so don't use an nsCOMPtr
nsITableLayout *tableLayoutObject;
res = GetTableLayoutObject(aTable, &tableLayoutObject);
if ((NS_SUCCEEDED(res)) && (nsnull!=tableLayoutObject))
{
// Note that this returns NS_TABLELAYOUT_CELL_NOT_FOUND when
// the index(es) are out of bounds
res = tableLayoutObject->GetCellDataAt(aRowIndex, aColIndex, aCell,
aStartRowIndex, aStartColIndex,
aRowSpan, aColSpan, aIsSelected);
}
return res;
}
// When all you want is the cell
NS_IMETHODIMP
nsHTMLEditor::GetCellAt(nsIDOMElement* aTable, PRInt32 aRowIndex, PRInt32 aColIndex, nsIDOMElement* &aCell)
{
PRInt32 aStartRowIndex, aStartColIndex, aRowSpan, aColSpan;
PRBool aIsSelected;
return GetCellDataAt(aTable, aRowIndex, aColIndex, aCell,
aStartRowIndex, aStartColIndex, aRowSpan, aColSpan, aIsSelected);
}
NS_IMETHODIMP
nsHTMLEditor::GetCellContext(nsCOMPtr<nsIDOMSelection> &aSelection,
nsCOMPtr<nsIDOMElement> &aTable, nsCOMPtr<nsIDOMElement> &aCell,
nsCOMPtr<nsIDOMNode> &aCellParent, PRInt32& aCellOffset,
PRInt32& aRow, PRInt32& aCol)
{
nsresult res = nsEditor::GetSelection(getter_AddRefs(aSelection));
if (NS_FAILED(res) || !aSelection)
return res;
// TODO: Should we look for the "first" cell instead?
// Messy! We would need to iterate through the selection to find the first enclosing cell
nsCOMPtr<nsIDOMNode> anchorNode;
if(NS_FAILED(aSelection->GetAnchorNode(getter_AddRefs(anchorNode))) || !anchorNode)
return NS_ERROR_FAILURE;
// Test if anchor is a cell node (should I bother to check header as well?
nsCOMPtr<nsIDOMHTMLTableCellElement> cellElement = do_QueryInterface(anchorNode);
if (cellElement)
{
aCell = do_QueryInterface(anchorNode);
} else {
// Get the anchor's first child, in case the selection is composed of cells
PRInt32 offset;
if (NS_FAILED(aSelection->GetAnchorOffset(&offset)))
return NS_ERROR_FAILURE;
nsCOMPtr<nsIDOMNode> anchorChild = GetChildAt(anchorNode, offset);
if(!anchorChild)
return NS_ERROR_FAILURE;
// Get the cell enclosing the selection anchor
if(NS_FAILED(GetElementOrParentByTagName("td", anchorChild, getter_AddRefs(aCell))) || !aCell)
return NS_ERROR_FAILURE;
}
if(NS_FAILED(GetElementOrParentByTagName("table", aCell, getter_AddRefs(aTable))) || !aTable)
return NS_ERROR_FAILURE;
if(NS_FAILED(aCell->GetParentNode(getter_AddRefs(aCellParent))) || !aCellParent)
return NS_ERROR_FAILURE;
// Get current cell location so we can put caret back there when done
res = GetCellIndexes(aCell, aRow, aCol);
if(NS_FAILED(res))
return res;
return GetChildOffset(aCell, aCellParent, aCellOffset);
}
NS_IMETHODIMP
nsHTMLEditor::SetCaretAfterTableEdit(nsIDOMElement* aTable, PRInt32 aCol, PRInt32 aRow, SetCaretSearchDirection aDirection)
{
nsresult res = NS_ERROR_NOT_INITIALIZED;
if (!aTable)
return res;
nsCOMPtr<nsIDOMSelection>selection;
res = nsEditor::GetSelection(getter_AddRefs(selection));
if (!NS_SUCCEEDED(res) || !selection)
{
#ifdef DEBUG_cmanske
printf("Selection not found after table manipulation!\n");
#endif
return NS_ERROR_FAILURE;
}
return res;
}

View File

@@ -0,0 +1,107 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL") you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "EditTxn.h"
#include "nsCOMPtr.h"
#include "nsIDOMNode.h"
#include "nsIDOMNodeList.h"
static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID);
static NS_DEFINE_IID(kITransactionIID, NS_ITRANSACTION_IID);
NS_IMPL_ADDREF(EditTxn)
NS_IMPL_RELEASE(EditTxn)
// note that aEditor is not refcounted
EditTxn::EditTxn()
{
NS_INIT_REFCNT();
}
EditTxn::~EditTxn()
{
}
NS_IMETHODIMP EditTxn::Do(void)
{
return NS_OK;
}
NS_IMETHODIMP EditTxn::Undo(void)
{
return NS_OK;
}
NS_IMETHODIMP EditTxn::Redo(void)
{
return Do();
}
NS_IMETHODIMP EditTxn::GetIsTransient(PRBool *aIsTransient)
{
if (nsnull!=aIsTransient)
*aIsTransient = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP EditTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
return NS_OK;
}
NS_IMETHODIMP EditTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP EditTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
*aString="";
return NS_OK;
}
NS_IMETHODIMP EditTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
*aString="";
return NS_OK;
}
NS_IMETHODIMP
EditTxn::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (NULL == aInstancePtr) {
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(kISupportsIID)) {
*aInstancePtr = (void*)(nsISupports*)this;
NS_ADDREF_THIS();
return NS_OK;
}
if (aIID.Equals(kITransactionIID)) {
*aInstancePtr = (void*)(nsITransaction*)this;
NS_ADDREF_THIS();
return NS_OK;
}
*aInstancePtr = 0;
return NS_NOINTERFACE;
}

View File

@@ -0,0 +1,66 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef EditTxn_h__
#define EditTxn_h__
#include "nsITransaction.h"
#include "nsCOMPtr.h"
#define EDIT_TXN_CID \
{/* c5ea31b0-ac48-11d2-86d8-000064657374 */ \
0xc5ea31b0, 0xac48, 0x11d2, \
{0x86, 0xd8, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74} }
/**
* base class for all document editing transactions.
* provides default concrete behavior for all nsITransaction methods.
* EditTxns optionally have a name. This name is for internal purposes only,
* it is never seen by the user or by any external entity.
*/
class EditTxn : public nsITransaction
{
public:
static const nsIID& GetCID() { static nsIID iid = EDIT_TXN_CID; return iid; }
NS_DECL_ISUPPORTS
EditTxn();
virtual ~EditTxn();
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Redo(void);
NS_IMETHOD GetIsTransient(PRBool *aIsTransient);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
};
#endif

View File

@@ -0,0 +1,112 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "IMECommitTxn.h"
#include "nsEditor.h"
nsIAtom *IMECommitTxn::gIMECommitTxnName = nsnull;
nsresult IMECommitTxn::ClassInit()
{
if (nsnull==gIMECommitTxnName)
gIMECommitTxnName = NS_NewAtom("NS_IMECommitTxn");
return NS_OK;
}
IMECommitTxn::IMECommitTxn()
: EditTxn()
{
}
IMECommitTxn::~IMECommitTxn()
{
}
NS_IMETHODIMP IMECommitTxn::Init(void)
{
return NS_OK;
}
NS_IMETHODIMP IMECommitTxn::Do(void)
{
#ifdef DEBUG_tague
printf("Do IME Commit");
#endif
return NS_OK;
}
NS_IMETHODIMP IMECommitTxn::Undo(void)
{
#ifdef DEBUG_TAGUE
printf("Undo IME Commit");
#endif
return NS_OK;
}
NS_IMETHODIMP IMECommitTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
#ifdef DEBUG_TAGUE
printf("Merge IME Commit");
#endif
*aDidMerge=PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP IMECommitTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP IMECommitTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Remove IMECommit: ";
}
return NS_OK;
}
NS_IMETHODIMP IMECommitTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Insert IMECommit: ";
}
return NS_OK;
}
/* ============= nsISupports implementation ====================== */
NS_IMETHODIMP
IMECommitTxn::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(IMECommitTxn::GetCID())) {
*aInstancePtr = (void*)(IMECommitTxn*)this;
NS_ADDREF_THIS();
return NS_OK;
}
return (EditTxn::QueryInterface(aIID, aInstancePtr));
}

View File

@@ -0,0 +1,82 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef IMECommitTxn_h__
#define IMECommitTxn_h__
#include "EditTxn.h"
#include "nsIDOMCharacterData.h"
#include "nsCOMPtr.h"
// {9C4994A1-281C-11d3-9EA3-0060089FE59B}
#define IME_COMMIT_TXN_CID \
{ 0x9c4994a1, 0x281c, 0x11d3, \
{ 0x9e, 0xa3, 0x0, 0x60, 0x8, 0x9f, 0xe5, 0x9b }}
/**
* A transaction representing an IME commit operation
*/
class IMECommitTxn : public EditTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = IME_COMMIT_TXN_CID; return iid; }
virtual ~IMECommitTxn();
static nsIAtom *gIMECommitTxnName;
/** initialize the transaction
*/
NS_IMETHOD Init(void);
private:
IMECommitTxn();
public:
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
// nsISupports declarations
// override QueryInterface to handle IMECommitTxn request
NS_IMETHOD QueryInterface(const nsIID& aIID, void** aInstancePtr);
/** must be called before any IMECommitTxn is instantiated */
static nsresult ClassInit();
protected:
friend class TransactionFactory;
friend class nsDerivedSafe<IMECommitTxn>; // work around for a compiler bug
};
#endif

View File

@@ -0,0 +1,310 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "IMETextTxn.h"
#include "IMECommitTxn.h"
#include "nsEditor.h"
#include "nsIDOMCharacterData.h"
#include "nsIDOMTextRange.h"
#include "nsIDOMTextRangeList.h"
#include "nsIDOMSelection.h"
#include "nsIPresShell.h"
#include "EditAggregateTxn.h"
static NS_DEFINE_IID(kIDOMSelectionIID, NS_IDOMSELECTION_IID);
nsIAtom *IMETextTxn::gIMETextTxnName = nsnull;
nsresult IMETextTxn::ClassInit()
{
if (nsnull==gIMETextTxnName)
gIMETextTxnName = NS_NewAtom("NS_IMETextTxn");
return NS_OK;
}
IMETextTxn::IMETextTxn()
: EditTxn()
{
}
IMETextTxn::~IMETextTxn()
{
mRangeList = do_QueryInterface(nsnull);
}
NS_IMETHODIMP IMETextTxn::Init(nsIDOMCharacterData *aElement,
PRUint32 aOffset,
PRUint32 aReplaceLength,
nsIDOMTextRangeList* aTextRangeList,
const nsString &aStringToInsert,
nsIPresShell *aPresShell)
{
mElement = do_QueryInterface(aElement);
mOffset = aOffset;
mReplaceLength = aReplaceLength;
mStringToInsert = aStringToInsert;
mPresShell = aPresShell;
mRangeList = do_QueryInterface(aTextRangeList);
mFixed = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP IMETextTxn::Do(void)
{
#ifdef DEBUG_TAGUE
printf("Do IME Text element = %p\n", mElement.get());
#endif
// advance caret: This requires the presentation shell to get the selection.
nsCOMPtr<nsIDOMSelection> selection;
nsresult result = mPresShell->GetSelection(SELECTION_NORMAL, getter_AddRefs(selection));
NS_ASSERTION(selection,"Could not get selection in IMEtextTxn::Do\n");
if (NS_SUCCEEDED(result) && selection) {
if (mReplaceLength==0) {
result = mElement->InsertData(mOffset,mStringToInsert);
} else {
result = mElement->ReplaceData(mOffset,mReplaceLength,mStringToInsert);
}
if (NS_SUCCEEDED(result)) {
result = CollapseTextSelection();
}
}
return result;
}
NS_IMETHODIMP IMETextTxn::Undo(void)
{
#ifdef DEBUG_TAGUE
printf("Undo IME Text element = %p\n", mElement.get());
#endif
nsresult result;
PRUint32 length = mStringToInsert.Length();
result = mElement->DeleteData(mOffset, length);
if (NS_SUCCEEDED(result))
{ // set the selection to the insertion point where the string was removed
nsCOMPtr<nsIDOMSelection> selection;
result = mPresShell->GetSelection(SELECTION_NORMAL, getter_AddRefs(selection));
if (NS_SUCCEEDED(result) && selection) {
result = selection->Collapse(mElement, mOffset);
NS_ASSERTION((NS_SUCCEEDED(result)), "selection could not be collapsed after undo of IME insert.");
}
}
return result;
}
NS_IMETHODIMP IMETextTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
nsresult result;
#ifdef DEBUG_TAGUE
printf("Merge IME Text element = %p\n", mElement.get());
#endif
//
// check to make sure we have valid return pointers
//
if ((nsnull==aDidMerge) && (nsnull==aTransaction))
{
return NS_OK;
}
//
// check to make sure we aren't fixed, if we are then nothing get's absorbed
//
if (mFixed) {
*aDidMerge = PR_FALSE;
return NS_OK;
}
//
// if aTransaction is another IMETextTxn then absorbe it
//
IMETextTxn* otherTxn = nsnull;
result = aTransaction->QueryInterface(IMETextTxn::GetCID(),(void**)&otherTxn);
if (otherTxn && result==NS_OK)
{
//
// we absorbe the next IME transaction by adopting it's insert string as our own
//
nsIDOMTextRangeList* newTextRangeList;
otherTxn->GetData(mStringToInsert,&newTextRangeList);
mRangeList = do_QueryInterface(newTextRangeList);
*aDidMerge = PR_TRUE;
#ifdef DEBUG_TAGUE
printf("IMETextTxn assimilated IMETextTxn:%p\n", aTransaction);
#endif
NS_RELEASE(otherTxn);
return NS_OK;
}
//
// second possible case is that we have a commit transaction
//
IMECommitTxn* commitTxn = nsnull;
result = aTransaction->QueryInterface(IMECommitTxn::GetCID(),(void**)&commitTxn);
if (commitTxn && result==NS_OK)
{
(void)CollapseTextSelectionOnCommit();
mFixed = PR_TRUE;
*aDidMerge = PR_TRUE; // absorbe the commit transaction
#ifdef DEBUG_TAGUE
printf("IMETextTxn assimilated IMECommitTxn%p\n", aTransaction);
#endif
NS_RELEASE(commitTxn);
return NS_OK;
}
*aDidMerge = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP IMETextTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP IMETextTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Remove Text: ";
*aString += mStringToInsert;
}
return NS_OK;
}
NS_IMETHODIMP IMETextTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Insert Text: ";
*aString += mStringToInsert;
}
return NS_OK;
}
/* ============= nsISupports implementation ====================== */
NS_IMETHODIMP
IMETextTxn::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(IMETextTxn::GetCID())) {
*aInstancePtr = (void*)(IMETextTxn*)this;
NS_ADDREF_THIS();
return NS_OK;
}
return (EditTxn::QueryInterface(aIID, aInstancePtr));
}
/* ============ protected methods ================== */
NS_IMETHODIMP IMETextTxn::GetData(nsString& aResult,nsIDOMTextRangeList** aTextRangeList)
{
aResult = mStringToInsert;
*aTextRangeList = mRangeList;
return NS_OK;
}
NS_IMETHODIMP IMETextTxn::CollapseTextSelection(void)
{
nsresult result;
PRBool haveSelectedRange, haveCaretPosition;
PRUint16 textRangeListLength,selectionStart,selectionEnd,
textRangeType, caretPosition, i;
nsIDOMTextRange* textRange;
haveSelectedRange = PR_FALSE;
haveCaretPosition = PR_FALSE;
#ifdef DEBUG_tague
PRUint16 listlen,start,stop,type;
nsIDOMTextRange* rangePtr;
result = mRangeList->GetLength(&listlen);
printf("nsIDOMTextRangeList[%p]\n",mRangeList);
for (i=0;i<listlen;i++) {
(void)mRangeList->Item(i,&rangePtr);
rangePtr->GetRangeStart(&start);
rangePtr->GetRangeEnd(&stop);
rangePtr->GetRangeType(&type);
printf("range[%d] start=%d end=%d type=",i,start,stop,type);
if (type==nsIDOMTextRange::TEXTRANGE_RAWINPUT) printf("TEXTRANGE_RAWINPUT\n");
if (type==nsIDOMTextRange::TEXTRANGE_SELECTEDRAWTEXT) printf("TEXTRANGE_SELECTEDRAWTEXT\n");
if (type==nsIDOMTextRange::TEXTRANGE_CONVERTEDTEXT) printf("TEXTRANGE_CONVERTEDTEXT\n");
if (type==nsIDOMTextRange::TEXTRANGE_SELECTEDCONVERTEDTEXT) printf("TEXTRANGE_SELECTEDCONVERTEDTEXT\n");
}
#endif
//
// run through the text range list
//
result = mRangeList->GetLength(&textRangeListLength);
if (NS_SUCCEEDED(result))
{
for(i=0;i<textRangeListLength;i++) {
result = mRangeList->Item(i,&textRange);
if (NS_SUCCEEDED(result))
{
result = textRange->GetRangeType(&textRangeType);
if (textRangeType==nsIDOMTextRange::TEXTRANGE_SELECTEDCONVERTEDTEXT)
{
haveSelectedRange = PR_TRUE;
textRange->GetRangeStart(&selectionStart);
textRange->GetRangeEnd(&selectionEnd);
}
if (textRangeType==nsIDOMTextRange::TEXTRANGE_CARETPOSITION)
{
haveCaretPosition = PR_TRUE;
textRange->GetRangeStart(&caretPosition);
}
}
}
}
nsCOMPtr<nsIDOMSelection> selection;
result = mPresShell->GetSelection(SELECTION_NORMAL, getter_AddRefs(selection));
if (NS_SUCCEEDED(result) && selection){
if (haveSelectedRange) {
result = selection->Collapse(mElement,mOffset+selectionStart);
result = selection->Extend(mElement,mOffset+selectionEnd);
} else {
if (haveCaretPosition)
result = selection->Collapse(mElement,mOffset+caretPosition);
else
result = selection->Collapse(mElement,mOffset+mStringToInsert.Length());
}
}
return result;
}
NS_IMETHODIMP IMETextTxn::CollapseTextSelectionOnCommit(void)
{
nsCOMPtr<nsIDOMSelection> selection;
nsresult result = mPresShell->GetSelection(SELECTION_NORMAL, getter_AddRefs(selection));
if (NS_SUCCEEDED(result) && selection){
result = selection->Collapse(mElement,mOffset+mStringToInsert.Length());
}
return result;
}

View File

@@ -0,0 +1,125 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef IMETextTxn_h__
#define IMETextTxn_h__
#include "EditTxn.h"
#include "nsIDOMCharacterData.h"
#include "nsIDOMTextRangeList.h"
#include "nsCOMPtr.h"
// {D4D25721-2813-11d3-9EA3-0060089FE59B}
#define IME_TEXT_TXN_CID \
{0xd4d25721, 0x2813, 0x11d3, \
{0x9e, 0xa3, 0x0, 0x60, 0x8, 0x9f, 0xe5, 0x9b }}
class nsIPresShell;
/**
* A transaction that inserts text into a content node.
*/
class IMETextTxn : public EditTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = IME_TEXT_TXN_CID; return iid; }
virtual ~IMETextTxn();
/** used to name aggregate transactions that consist only of a single IMETextTxn,
* or a DeleteSelection followed by an IMETextTxn.
*/
static nsIAtom *gIMETextTxnName;
/** initialize the transaction
* @param aElement the text content node
* @param aOffset the location in aElement to do the insertion
* @param aReplaceLength the length of text to replace (0= no replacement)
* @param aString the new text to insert
* @param aPresShell used to get and set the selection
*/
NS_IMETHOD Init(nsIDOMCharacterData *aElement,
PRUint32 aOffset,
PRUint32 aReplaceLength,
nsIDOMTextRangeList* aTextRangeList,
const nsString& aString,
nsIPresShell* aPresShell);
private:
IMETextTxn();
public:
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
// nsISupports declarations
// override QueryInterface to handle IMETextTxn request
NS_IMETHOD QueryInterface(const nsIID& aIID, void** aInstancePtr);
/** return the string data associated with this transaction */
NS_IMETHOD GetData(nsString& aResult, nsIDOMTextRangeList** aTextRangeList);
/** must be called before any IMETextTxn is instantiated */
static nsresult ClassInit();
protected:
NS_IMETHOD CollapseTextSelection(void);
NS_IMETHOD CollapseTextSelectionOnCommit(void);
/** the text element to operate upon */
nsCOMPtr<nsIDOMCharacterData> mElement;
/** the offsets into mElement where the insertion should be placed*/
PRUint32 mOffset;
PRUint32 mReplaceLength;
/** the text to insert into mElement at mOffset */
nsString mStringToInsert;
/** the range list **/
nsCOMPtr<nsIDOMTextRangeList> mRangeList;
/** the presentation shell, which we'll need to get the selection */
nsIPresShell* mPresShell;
PRBool mFixed;
friend class TransactionFactory;
friend class nsDerivedSafe<IMETextTxn>; // work around for a compiler bug
};
#endif

View File

@@ -0,0 +1,148 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "InsertElementTxn.h"
#include "nsIDOMSelection.h"
#include "nsIContent.h"
#ifdef NS_DEBUG
static PRBool gNoisy = PR_FALSE;
#else
static const PRBool gNoisy = PR_FALSE;
#endif
InsertElementTxn::InsertElementTxn()
: EditTxn()
{
}
NS_IMETHODIMP InsertElementTxn::Init(nsIDOMNode *aNode,
nsIDOMNode *aParent,
PRInt32 aOffset,
nsIEditor *aEditor)
{
NS_ASSERTION(aNode && aParent && aEditor, "bad arg");
if (!aNode || !aParent || !aEditor)
return NS_ERROR_NULL_POINTER;
mNode = do_QueryInterface(aNode);
mParent = do_QueryInterface(aParent);
mOffset = aOffset;
mEditor = aEditor;
if (!mNode || !mParent || !mEditor)
return NS_ERROR_INVALID_ARG;
return NS_OK;
}
InsertElementTxn::~InsertElementTxn()
{
}
NS_IMETHODIMP InsertElementTxn::Do(void)
{
if (gNoisy)
{
nsCOMPtr<nsIContent>nodeAsContent = do_QueryInterface(mNode);
nsCOMPtr<nsIContent>parentAsContent = do_QueryInterface(mParent);
printf("%p Do Insert Element of %p into parent %p at offset %d\n",
this, nodeAsContent.get(), parentAsContent.get(), mOffset);
}
if (!mNode || !mParent)
return NS_ERROR_NULL_POINTER;
nsresult result;
nsCOMPtr<nsIDOMNode>refNode;
//if (0!=mOffset)
{ // get a ref node
PRInt32 i=0;
result = mParent->GetFirstChild(getter_AddRefs(refNode));
if (NS_SUCCEEDED(result) && refNode)
{
for (; i<mOffset; i++)
{
nsCOMPtr<nsIDOMNode>nextSib;
result = refNode->GetNextSibling(getter_AddRefs(nextSib));
if (NS_FAILED(result)) {
break; // couldn't get a next sibling, so make aNode the first child
}
refNode = do_QueryInterface(nextSib);
if (!refNode) {
break; // couldn't get a next sibling, so make aNode the first child
}
}
}
}
nsCOMPtr<nsIDOMNode> resultNode;
result = mParent->InsertBefore(mNode, refNode, getter_AddRefs(resultNode));
if (NS_SUCCEEDED(result) && resultNode)
{
nsCOMPtr<nsIDOMSelection> selection;
result = mEditor->GetSelection(getter_AddRefs(selection));
if ((NS_SUCCEEDED(result)) && selection)
{ // place the selection just after the inserted element
selection->Collapse(mParent, mOffset+1);
//selection->Extend(mParent, mOffset+1);
}
}
return result;
}
NS_IMETHODIMP InsertElementTxn::Undo(void)
{
if (gNoisy) { printf("%p Undo Insert Element of %p into parent %p at offset %d\n",
this, mNode.get(), mParent.get(), mOffset); }
if (!mNode || !mParent)
return NS_ERROR_NULL_POINTER;
nsCOMPtr<nsIDOMNode> resultNode;
nsresult result = mParent->RemoveChild(mNode, getter_AddRefs(resultNode));
return result;
}
NS_IMETHODIMP InsertElementTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
if (nsnull!=aDidMerge)
*aDidMerge=PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP InsertElementTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP InsertElementTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Remove Element: ";
}
return NS_OK;
}
NS_IMETHODIMP InsertElementTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Insert Element: ";
}
return NS_OK;
}

View File

@@ -0,0 +1,88 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef InsertElementTxn_h__
#define InsertElementTxn_h__
#include "EditTxn.h"
#include "nsIEditor.h"
#include "nsIDOMNode.h"
#include "nsCOMPtr.h"
#define INSERT_ELEMENT_TXN_CID \
{/* b5762440-cbb0-11d2-86db-000064657374 */ \
0xb5762440, 0xcbb0, 0x11d2, \
{0x86, 0xdb, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74} }
/**
* A transaction that inserts a single element
*/
class InsertElementTxn : public EditTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = INSERT_ELEMENT_TXN_CID; return iid; }
/** initialize the transaction.
* @param aNode the node to insert
* @param aParent the node to insert into
* @param aOffset the offset in aParent to insert aNode
*/
NS_IMETHOD Init(nsIDOMNode *aNode,
nsIDOMNode *aParent,
PRInt32 aOffset,
nsIEditor *aEditor);
private:
InsertElementTxn();
public:
virtual ~InsertElementTxn();
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
protected:
/** the element to insert */
nsCOMPtr<nsIDOMNode> mNode;
/** the node into which the new node will be inserted */
nsCOMPtr<nsIDOMNode> mParent;
/** the editor for this transaction */
nsIEditor* mEditor;
/** the index in mParent for the new node */
PRInt32 mOffset;
friend class TransactionFactory;
};
#endif

View File

@@ -0,0 +1,235 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "InsertTextTxn.h"
#include "nsEditor.h"
#include "nsIDOMCharacterData.h"
#include "nsIDOMSelection.h"
#include "nsIPresShell.h"
#include "EditAggregateTxn.h"
static NS_DEFINE_IID(kIDOMSelectionIID, NS_IDOMSELECTION_IID);
#ifdef NS_DEBUG
static PRBool gNoisy = PR_FALSE;
#else
static const PRBool gNoisy = PR_FALSE;
#endif
nsIAtom *InsertTextTxn::gInsertTextTxnName;
nsresult InsertTextTxn::ClassInit()
{
if (nsnull==gInsertTextTxnName)
gInsertTextTxnName = NS_NewAtom("NS_InsertTextTxn");
return NS_OK;
}
InsertTextTxn::InsertTextTxn()
: EditTxn()
{
}
InsertTextTxn::~InsertTextTxn()
{
}
NS_IMETHODIMP InsertTextTxn::Init(nsIDOMCharacterData *aElement,
PRUint32 aOffset,
const nsString &aStringToInsert,
nsIPresShell *aPresShell)
{
#if 0 //def DEBUG_cmanske
nsString text;
aElement->GetData(text);
printf("InsertTextTxn: Offset to insert at = %d. Text of the node to insert into:\n", aOffset);
wprintf(text.GetUnicode());
printf("\n");
#endif
mElement = do_QueryInterface(aElement);
mOffset = aOffset;
mStringToInsert = aStringToInsert;
mPresShell = aPresShell;
return NS_OK;
}
NS_IMETHODIMP InsertTextTxn::Do(void)
{
if (gNoisy) { printf("Do Insert Text element = %p\n", mElement.get()); }
// advance caret: This requires the presentation shell to get the selection.
nsCOMPtr<nsIDOMSelection> selection;
nsresult result = mPresShell->GetSelection(SELECTION_NORMAL, getter_AddRefs(selection));
NS_ASSERTION(selection,"Could not get selection in InsertTextTxn::Do\n");
if (NS_SUCCEEDED(result) && selection) {
result = mElement->InsertData(mOffset, mStringToInsert);
if (NS_SUCCEEDED(result)) {
result = selection->Collapse(mElement, mOffset+mStringToInsert.Length());
NS_ASSERTION((NS_SUCCEEDED(result)), "selection could not be collapsed after insert.");
}
}
return result;
}
NS_IMETHODIMP InsertTextTxn::Undo(void)
{
if (gNoisy) { printf("Undo Insert Text element = %p\n", mElement.get()); }
nsresult result;
PRUint32 length = mStringToInsert.Length();
result = mElement->DeleteData(mOffset, length);
if (NS_SUCCEEDED(result))
{ // set the selection to the insertion point where the string was removed
nsCOMPtr<nsIDOMSelection> selection;
result = mPresShell->GetSelection(SELECTION_NORMAL, getter_AddRefs(selection));
if (NS_SUCCEEDED(result) && selection) {
result = selection->Collapse(mElement, mOffset);
NS_ASSERTION((NS_SUCCEEDED(result)), "selection could not be collapsed after undo of insert.");
}
}
return result;
}
NS_IMETHODIMP InsertTextTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
// set out param default value
if (nsnull!=aDidMerge)
*aDidMerge=PR_FALSE;
nsresult result = NS_OK;
if ((nsnull!=aDidMerge) && (nsnull!=aTransaction))
{
// if aTransaction isa InsertTextTxn, and if the selection hasn't changed,
// then absorb it
InsertTextTxn *otherInsTxn = nsnull;
aTransaction->QueryInterface(InsertTextTxn::GetCID(), (void **)&otherInsTxn);
if (otherInsTxn)
{
if (PR_TRUE==IsSequentialInsert(otherInsTxn))
{
nsAutoString otherData;
otherInsTxn->GetData(otherData);
mStringToInsert += otherData;
*aDidMerge = PR_TRUE;
if (gNoisy) { printf("InsertTextTxn assimilated %p\n", aTransaction); }
}
NS_RELEASE(otherInsTxn);
}
else
{ // the next InsertTextTxn might be inside an aggregate that we have special knowledge of
EditAggregateTxn *otherTxn = nsnull;
aTransaction->QueryInterface(EditAggregateTxn::GetCID(), (void **)&otherTxn);
if (otherTxn)
{
nsCOMPtr<nsIAtom> txnName;
otherTxn->GetName(getter_AddRefs(txnName));
if (txnName && txnName.get()==gInsertTextTxnName)
{ // yep, it's one of ours. By definition, it must contain only
// another aggregate with a single child,
// or a single InsertTextTxn
nsCOMPtr<EditTxn> childTxn;
otherTxn->GetTxnAt(0, getter_AddRefs(childTxn));
if (childTxn)
{
nsCOMPtr<InsertTextTxn> otherInsertTxn;
otherInsertTxn = do_QueryInterface(childTxn);
if (otherInsertTxn)
{
if (PR_TRUE==IsSequentialInsert(otherInsertTxn))
{
nsAutoString otherData;
otherInsertTxn->GetData(otherData);
mStringToInsert += otherData;
*aDidMerge = PR_TRUE;
if (gNoisy) { printf("InsertTextTxn assimilated %p\n", aTransaction); }
}
}
}
}
NS_RELEASE(otherTxn);
}
}
}
return result;
}
NS_IMETHODIMP InsertTextTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP InsertTextTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Remove Text: ";
*aString += mStringToInsert;
}
return NS_OK;
}
NS_IMETHODIMP InsertTextTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Insert Text: ";
*aString += mStringToInsert;
}
return NS_OK;
}
/* ============= nsISupports implementation ====================== */
NS_IMETHODIMP
InsertTextTxn::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(InsertTextTxn::GetCID())) {
*aInstancePtr = (void*)(InsertTextTxn*)this;
NS_ADDREF_THIS();
return NS_OK;
}
return (EditTxn::QueryInterface(aIID, aInstancePtr));
}
/* ============ protected methods ================== */
NS_IMETHODIMP InsertTextTxn::GetData(nsString& aResult)
{
aResult = mStringToInsert;
return NS_OK;
}
PRBool InsertTextTxn::IsSequentialInsert(InsertTextTxn *aOtherTxn)
{
NS_ASSERTION(nsnull!=aOtherTxn, "null param");
PRBool result=PR_FALSE;
if (nsnull!=aOtherTxn)
{
if (aOtherTxn->mElement == mElement)
{
// here, we need to compare offsets.
PRInt32 length = mStringToInsert.Length();
if (aOtherTxn->mOffset==(mOffset+length))
{
result = PR_TRUE;
}
}
}
return result;
}

View File

@@ -0,0 +1,112 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef InsertTextTxn_h__
#define InsertTextTxn_h__
#include "EditTxn.h"
#include "nsIDOMCharacterData.h"
#include "nsCOMPtr.h"
#define INSERT_TEXT_TXN_CID \
{/* 93276f00-ab2c-11d2-8f4b-006008159b0c*/ \
0x93276f00, 0xab2c, 0x11d2, \
{0x8f, 0xb4, 0x0, 0x60, 0x8, 0x15, 0x9b, 0xc} }
class nsIPresShell;
/**
* A transaction that inserts text into a content node.
*/
class InsertTextTxn : public EditTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = INSERT_TEXT_TXN_CID; return iid; }
virtual ~InsertTextTxn();
/** used to name aggregate transactions that consist only of a single InsertTextTxn,
* or a DeleteSelection followed by an InsertTextTxn.
*/
static nsIAtom *gInsertTextTxnName;
/** initialize the transaction
* @param aElement the text content node
* @param aOffset the location in aElement to do the insertion
* @param aString the new text to insert
* @param aPresShell used to get and set the selection
*/
NS_IMETHOD Init(nsIDOMCharacterData *aElement,
PRUint32 aOffset,
const nsString& aString,
nsIPresShell* aPresShell);
private:
InsertTextTxn();
public:
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
// nsISupports declarations
// override QueryInterface to handle InsertTextTxn request
NS_IMETHOD QueryInterface(const nsIID& aIID, void** aInstancePtr);
/** return the string data associated with this transaction */
NS_IMETHOD GetData(nsString& aResult);
/** must be called before any InsertTextTxn is instantiated */
static nsresult ClassInit();
protected:
/** return PR_TRUE if aOtherTxn immediately follows this txn */
virtual PRBool IsSequentialInsert(InsertTextTxn *aOtherTxn);
/** the text element to operate upon */
nsCOMPtr<nsIDOMCharacterData> mElement;
/** the offset into mElement where the insertion is to take place */
PRUint32 mOffset;
/** the text to insert into mElement at mOffset */
nsString mStringToInsert;
/** the presentation shell, which we'll need to get the selection */
nsIPresShell* mPresShell;
friend class TransactionFactory;
friend class nsDerivedSafe<InsertTextTxn>; // work around for a compiler bug
};
#endif

View File

@@ -0,0 +1,181 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "JoinElementTxn.h"
#include "nsEditor.h"
#include "nsIDOMNodeList.h"
#include "nsIDOMCharacterData.h"
#include "nsIDOMSelection.h"
#ifdef NS_DEBUG
static PRBool gNoisy = PR_FALSE;
#else
static const PRBool gNoisy = PR_FALSE;
#endif
JoinElementTxn::JoinElementTxn()
: EditTxn()
{
}
NS_IMETHODIMP JoinElementTxn::Init(nsIEditor *aEditor,
nsIDOMNode *aLeftNode,
nsIDOMNode *aRightNode)
{
mEditor = aEditor;
mLeftNode = do_QueryInterface(aLeftNode);
mRightNode = do_QueryInterface(aRightNode);
mOffset=0;
return NS_OK;
}
JoinElementTxn::~JoinElementTxn()
{
}
// After Do() and Redo(), the left node is removed from the content tree and right node remains.
NS_IMETHODIMP JoinElementTxn::Do(void)
{
if (gNoisy) { printf("%p Do Join of %p and %p\n", this, mLeftNode.get(), mRightNode.get()); }
nsresult result;
if ((mLeftNode) && (mRightNode))
{ // get the parent node
nsCOMPtr<nsIDOMNode>leftParent;
result = mLeftNode->GetParentNode(getter_AddRefs(leftParent));
if ((NS_SUCCEEDED(result)) && (leftParent))
{ // verify that mLeftNode and mRightNode have the same parent
nsCOMPtr<nsIDOMNode>rightParent;
result = mRightNode->GetParentNode(getter_AddRefs(rightParent));
if ((NS_SUCCEEDED(result)) && (rightParent))
{
if (leftParent==rightParent)
{
mParent= do_QueryInterface(leftParent); // set this instance mParent.
// Other methods will see a non-null mParent and know all is well
nsCOMPtr<nsIDOMNodeList> childNodes;
result = mLeftNode->GetChildNodes(getter_AddRefs(childNodes));
if ((NS_SUCCEEDED(result)) && (childNodes)) {
childNodes->GetLength(&mOffset);
}
else
{
nsCOMPtr<nsIDOMCharacterData> leftNodeAsText;
leftNodeAsText = do_QueryInterface(mLeftNode);
if (leftNodeAsText) {
leftNodeAsText->GetLength(&mOffset);
}
}
result = nsEditor::JoinNodesImpl(mRightNode, mLeftNode, mParent, PR_FALSE);
if (NS_SUCCEEDED(result))
{
if (gNoisy) { printf(" left node = %p removed\n", mLeftNode.get()); }
nsCOMPtr<nsIDOMSelection>selection;
mEditor->GetSelection(getter_AddRefs(selection));
if (selection)
{
selection->Collapse(mRightNode, mOffset);
}
}
}
else
{
NS_ASSERTION(PR_FALSE, "2 nodes do not have same parent");
return NS_ERROR_INVALID_ARG;
}
}
}
}
return result;
}
//XXX: what if instead of split, we just deleted the unneeded children of mRight
// and re-inserted mLeft?
NS_IMETHODIMP JoinElementTxn::Undo(void)
{
if (gNoisy) { printf("%p Undo Join, right node = %p\n", this, mRightNode.get()); }
NS_ASSERTION(mRightNode && mLeftNode && mParent, "bad state");
if (!mRightNode || !mLeftNode || !mParent) {
return NS_ERROR_NOT_INITIALIZED;
}
nsresult result;
nsCOMPtr<nsIDOMNode>resultNode;
// first, massage the existing node so it is in its post-split state
nsCOMPtr<nsIDOMCharacterData>rightNodeAsText;
rightNodeAsText = do_QueryInterface(mRightNode);
if (rightNodeAsText)
{
result = rightNodeAsText->DeleteData(0, mOffset);
}
else
{
nsCOMPtr<nsIDOMNode>child;
nsCOMPtr<nsIDOMNode>nextSibling;
result = mRightNode->GetFirstChild(getter_AddRefs(child));
PRUint32 i;
for (i=0; i<mOffset; i++)
{
if (NS_FAILED(result)) {return result;}
if (!child) {return NS_ERROR_NULL_POINTER;}
child->GetNextSibling(getter_AddRefs(nextSibling));
result = mLeftNode->AppendChild(child, getter_AddRefs(resultNode));
child = do_QueryInterface(nextSibling);
}
}
// second, re-insert the left node into the tree
result = mParent->InsertBefore(mLeftNode, mRightNode, getter_AddRefs(resultNode));
return result;
}
NS_IMETHODIMP JoinElementTxn::GetIsTransient(PRBool *aIsTransient)
{
if (nsnull!=aIsTransient)
*aIsTransient = PR_FALSE;
return NS_OK;
}
nsresult JoinElementTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
if (nsnull!=aDidMerge)
*aDidMerge=PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP JoinElementTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP JoinElementTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Join Element";
}
return NS_OK;
}
NS_IMETHODIMP JoinElementTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Split Element";
}
return NS_OK;
}

View File

@@ -0,0 +1,98 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef JoinElementTxn_h__
#define JoinElementTxn_h__
#include "EditTxn.h"
#include "nsIDOMNode.h"
#include "nsCOMPtr.h"
#include "nsIEditor.h"
#define JOIN_ELEMENT_TXN_CID \
{/* 9bc5f9f0-ac48-11d2-86d8-000064657374 */ \
0x9bc5f9f0, 0xac48, 0x11d2, \
{0x86, 0xd8, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74} }
/**
* A transaction that joins two elements E1 (left node) and E2 (right node)
* into a single node E.
* The children of E are the children of E1 followed by the children of E2.
* After Do() and Redo(), E1 is removed from the content tree and E2 remains.
*/
class JoinElementTxn : public EditTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = JOIN_ELEMENT_TXN_CID; return iid; }
/** initialize the transaction
* @param aEditor the provider of core editing operations
* @param aLeftNode the first of two nodes to join
* @param aRightNode the second of two nodes to join
*/
NS_IMETHOD Init(nsIEditor *aEditor,
nsIDOMNode *aLeftNode,
nsIDOMNode *aRightNode);
protected:
JoinElementTxn();
public:
virtual ~JoinElementTxn();
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
// NS_IMETHOD Redo(void);
NS_IMETHOD GetIsTransient(PRBool *aIsTransient);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
protected:
/** the elements to operate upon.
* After the merge, mRightNode remains and mLeftNode is removed from the content tree.
*/
nsCOMPtr<nsIDOMNode> mLeftNode;
nsCOMPtr<nsIDOMNode> mRightNode;
/** the offset into mNode where the children of mElement are split (for undo).<BR>
* mOffset is the index of the first child in the right node.
* -1 means the left node had no children.
*/
PRUint32 mOffset;
/** the parent node containing mLeftNode and mRightNode */
nsCOMPtr<nsIDOMNode> mParent;
nsIEditor* mEditor;
friend class TransactionFactory;
};
#endif

View File

@@ -0,0 +1,78 @@
#!gmake
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (the "NPL"); you may not use this file except in
# compliance with the NPL. You may obtain a copy of the NPL at
# http://www.mozilla.org/NPL/
#
# Software distributed under the NPL is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
# for the specific language governing rights and limitations under the
# NPL.
#
# The Initial Developer of this code under the NPL is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All Rights
# Reserved.
DEPTH=../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
LIBRARY_NAME = ender
IS_COMPONENT = 1
CPPSRCS = \
nsEditor.cpp \
nsEditorUtils.cpp \
nsEditorRegistration.cpp \
nsTextEditRules.cpp \
TextEditorTest.cpp \
nsHTMLEditRules.cpp \
nsEditorEventListeners.cpp \
nsEditProperty.cpp \
nsEditorFactory.cpp \
nsHTMLEditor.cpp \
ChangeAttributeTxn.cpp \
EditTxn.cpp \
EditAggregateTxn.cpp \
EditTable.cpp \
InsertTextTxn.cpp \
nsInsertHTMLTxn.cpp \
PlaceholderTxn.cpp \
DeleteTextTxn.cpp \
CreateElementTxn.cpp \
InsertElementTxn.cpp \
DeleteElementTxn.cpp \
DeleteRangeTxn.cpp \
SplitElementTxn.cpp \
JoinElementTxn.cpp \
nsStyleSheetTxns.cpp \
TransactionFactory.cpp \
TypeInState.cpp \
nsInternetCiter.cpp \
nsAOLCiter.cpp \
nsInterfaceState.cpp \
nsEditorShell.cpp \
nsEditorShellFactory.cpp \
IMETextTxn.cpp \
IMECommitTxn.cpp \
$(NULL)
ifdef ENABLE_JS_EDITOR_LOG
DEFINES += -DENABLE_JS_EDITOR_LOG
CPPSRCS += \
nsJSEditorLog.cpp \
nsJSTxnLog.cpp \
$(NULL)
endif
MODULE = editor
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk

View File

@@ -0,0 +1,76 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "PlaceholderTxn.h"
#include "nsVoidArray.h"
#ifdef NS_DEBUG
static PRBool gNoisy = PR_TRUE;
#else
static const PRBool gNoisy = PR_FALSE;
#endif
PlaceholderTxn::PlaceholderTxn()
: EditAggregateTxn()
{
mAbsorb=PR_TRUE;
}
PlaceholderTxn::~PlaceholderTxn()
{
}
NS_IMETHODIMP PlaceholderTxn::Do(void)
{
if (gNoisy) { printf("PlaceholderTxn Do\n"); }
return NS_OK;
}
NS_IMETHODIMP PlaceholderTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
// set out param default value
if (nsnull!=aDidMerge)
*aDidMerge=PR_FALSE;
nsresult result = NS_OK;
if ((nsnull!=aDidMerge) && (nsnull!=aTransaction))
{
EditTxn *editTxn = (EditTxn*)aTransaction; //XXX: hack, not safe! need nsIEditTransaction!
if (PR_TRUE==mAbsorb)
{ // yep, it's one of ours. Assimilate it.
AppendChild(editTxn);
*aDidMerge = PR_TRUE;
if (gNoisy) { printf("Placeholder txn assimilated %p\n", aTransaction); }
}
else
{ // let our last child txn make the choice
PRInt32 count = mChildren->Count();
if (0<count)
{
EditTxn *lastTxn = (EditTxn*)(mChildren->ElementAt(count-1));
if (lastTxn)
{
lastTxn->Merge(aDidMerge, aTransaction);
}
}
}
}
return result;
}

View File

@@ -0,0 +1,69 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef AggregatePlaceholderTxn_h__
#define AggregatePlaceholderTxn_h__
#include "EditAggregateTxn.h"
#define PLACEHOLDER_TXN_CID \
{/* {0CE9FB00-D9D1-11d2-86DE-000064657374} */ \
0x0CE9FB00, 0xD9D1, 0x11d2, \
{0x86, 0xde, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74} }
/**
* An aggregate transaction that knows how to absorb all subsequent
* transactions with the same name. This transaction does not "Do" anything.
* But it absorbs other transactions via merge, and can undo/redo the
* transactions it has absorbed.
*/
class PlaceholderTxn : public EditAggregateTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = PLACEHOLDER_TXN_CID; return iid; }
private:
PlaceholderTxn();
public:
virtual ~PlaceholderTxn();
NS_IMETHOD Do(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD SetAbsorb(PRBool aAbsorb);
friend class TransactionFactory;
protected:
PRBool mAbsorb;
};
inline NS_IMETHODIMP PlaceholderTxn::SetAbsorb(PRBool aAbsorb)
{
mAbsorb = aAbsorb;
return NS_OK;
};
#endif

View File

@@ -0,0 +1,226 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "SplitElementTxn.h"
#include "nsEditor.h"
#include "nsIDOMNode.h"
#include "nsIDOMSelection.h"
#include "nsIDOMCharacterData.h"
#ifdef NS_DEBUG
static PRBool gNoisy = PR_FALSE;
#else
static const PRBool gNoisy = PR_FALSE;
#endif
// note that aEditor is not refcounted
SplitElementTxn::SplitElementTxn()
: EditTxn()
{
}
NS_IMETHODIMP SplitElementTxn::Init(nsIEditor *aEditor,
nsIDOMNode *aNode,
PRInt32 aOffset)
{
mEditor = aEditor;
mExistingRightNode = do_QueryInterface(aNode);
mOffset = aOffset;
return NS_OK;
}
SplitElementTxn::~SplitElementTxn()
{
}
NS_IMETHODIMP SplitElementTxn::Do(void)
{
if (gNoisy) { printf("%p Do Split of node %p offset %d\n", this, mExistingRightNode.get(), mOffset); }
NS_ASSERTION(mExistingRightNode, "bad state");
if (!mExistingRightNode) {
return NS_ERROR_NOT_INITIALIZED;
}
// create a new node
nsresult result = mExistingRightNode->CloneNode(PR_FALSE, getter_AddRefs(mNewLeftNode));
NS_ASSERTION(((NS_SUCCEEDED(result)) && (mNewLeftNode)), "could not create element.");
if ((NS_SUCCEEDED(result)) && (mNewLeftNode))
{
if (gNoisy) { printf(" created left node = %p\n", mNewLeftNode.get()); }
// get the parent node
result = mExistingRightNode->GetParentNode(getter_AddRefs(mParent));
// insert the new node
if ((NS_SUCCEEDED(result)) && (mParent))
{
result = nsEditor::SplitNodeImpl(mExistingRightNode, mOffset, mNewLeftNode, mParent);
if (NS_SUCCEEDED(result) && mNewLeftNode)
{
nsCOMPtr<nsIDOMSelection>selection;
mEditor->GetSelection(getter_AddRefs(selection));
if (selection)
{
selection->Collapse(mNewLeftNode, mOffset);
}
}
else {
result = NS_ERROR_NOT_IMPLEMENTED;
}
}
}
return result;
}
NS_IMETHODIMP SplitElementTxn::Undo(void)
{
if (gNoisy) {
printf("%p Undo Split of existing node %p and new node %p offset %d\n",
this, mExistingRightNode.get(), mNewLeftNode.get(), mOffset);
}
NS_ASSERTION(mExistingRightNode && mNewLeftNode && mParent, "bad state");
if (!mExistingRightNode || !mNewLeftNode || !mParent) {
return NS_ERROR_NOT_INITIALIZED;
}
// this assumes Do inserted the new node in front of the prior existing node
nsresult result;
result = nsEditor::JoinNodesImpl(mExistingRightNode, mNewLeftNode, mParent, PR_FALSE);
if (gNoisy)
{
printf("** after join left child node %p into right node %p\n", mNewLeftNode.get(), mExistingRightNode.get());
if (gNoisy) {mEditor->DebugDumpContent(); } // DEBUG
}
if (NS_SUCCEEDED(result))
{
if (gNoisy) { printf(" left node = %p removed\n", mNewLeftNode.get()); }
nsCOMPtr<nsIDOMSelection>selection;
mEditor->GetSelection(getter_AddRefs(selection));
if (selection)
{
selection->Collapse(mExistingRightNode, mOffset);
}
}
else {
result = NS_ERROR_NOT_IMPLEMENTED;
}
return result;
}
/* redo cannot simply resplit the right node, because subsequent transactions
* on the redo stack may depend on the left node existing in its previous state.
*/
NS_IMETHODIMP SplitElementTxn::Redo(void)
{
NS_ASSERTION(mExistingRightNode && mNewLeftNode && mParent, "bad state");
if (!mExistingRightNode || !mNewLeftNode || !mParent) {
return NS_ERROR_NOT_INITIALIZED;
}
if (gNoisy) {
printf("%p Redo Split of existing node %p and new node %p offset %d\n",
this, mExistingRightNode.get(), mNewLeftNode.get(), mOffset);
if (gNoisy) {mEditor->DebugDumpContent(); } // DEBUG
}
nsresult result;
nsCOMPtr<nsIDOMNode>resultNode;
// first, massage the existing node so it is in its post-split state
nsCOMPtr<nsIDOMCharacterData>rightNodeAsText;
rightNodeAsText = do_QueryInterface(mExistingRightNode);
if (rightNodeAsText)
{
result = rightNodeAsText->DeleteData(0, mOffset);
if (gNoisy)
{
printf("** after delete of text in right text node %p offset %d\n", rightNodeAsText.get(), mOffset);
if (gNoisy) {mEditor->DebugDumpContent(); } // DEBUG
}
}
else
{
nsCOMPtr<nsIDOMNode>child;
nsCOMPtr<nsIDOMNode>nextSibling;
result = mExistingRightNode->GetFirstChild(getter_AddRefs(child));
PRInt32 i;
for (i=0; i<mOffset; i++)
{
if (NS_FAILED(result)) {return result;}
if (!child) {return NS_ERROR_NULL_POINTER;}
child->GetNextSibling(getter_AddRefs(nextSibling));
result = mExistingRightNode->RemoveChild(child, getter_AddRefs(resultNode));
if (NS_SUCCEEDED(result))
{
result = mNewLeftNode->AppendChild(child, getter_AddRefs(resultNode));
if (gNoisy)
{
printf("** move child node %p from right node %p to left node %p\n", child.get(), mExistingRightNode.get(), mNewLeftNode.get());
if (gNoisy) {mEditor->DebugDumpContent(); } // DEBUG
}
}
child = do_QueryInterface(nextSibling);
}
}
// second, re-insert the left node into the tree
result = mParent->InsertBefore(mNewLeftNode, mExistingRightNode, getter_AddRefs(resultNode));
if (gNoisy)
{
printf("** reinsert left child node %p before right node %p\n", mNewLeftNode.get(), mExistingRightNode.get());
if (gNoisy) {mEditor->DebugDumpContent(); } // DEBUG
}
return result;
}
NS_IMETHODIMP SplitElementTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
if (nsnull!=aDidMerge)
*aDidMerge=PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP SplitElementTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP SplitElementTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Join Element";
}
return NS_OK;
}
NS_IMETHODIMP SplitElementTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Split Element";
}
return NS_OK;
}
NS_IMETHODIMP SplitElementTxn::GetNewNode(nsIDOMNode **aNewNode)
{
if (!aNewNode)
return NS_ERROR_NULL_POINTER;
if (!mNewLeftNode)
return NS_ERROR_NOT_INITIALIZED;
*aNewNode = mNewLeftNode;
NS_ADDREF(*aNewNode);
return NS_OK;
}

View File

@@ -0,0 +1,96 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef SplitElementTxn_h__
#define SplitElementTxn_h__
#include "EditTxn.h"
#include "nsIDOMNode.h"
#include "nsCOMPtr.h"
#include "nsIEditor.h"
#define SPLIT_ELEMENT_TXN_CID \
{/* 690c6290-ac48-11d2-86d8-000064657374 */ \
0x690c6290, 0xac48, 0x11d2, \
{0x86, 0xd8, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74} }
/**
* A transaction that splits an element E into two identical nodes, E1 and E2
* with the children of E divided between E1 and E2.
*/
class SplitElementTxn : public EditTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = SPLIT_ELEMENT_TXN_CID; return iid; }
/** initialize the transaction.
* @param aEditor the provider of core editing operations
* @param aNode the node to split
* @param aOffset the location within aNode to do the split.
* aOffset may refer to children of aNode, or content of aNode.
* The left node will have child|content 0..aOffset-1.
*/
NS_IMETHOD Init (nsIEditor *aEditor,
nsIDOMNode *aNode,
PRInt32 aOffset);
protected:
SplitElementTxn();
public:
virtual ~SplitElementTxn();
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Redo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
NS_IMETHOD GetNewNode(nsIDOMNode **aNewNode);
protected:
/** the element to operate upon */
nsCOMPtr<nsIDOMNode> mExistingRightNode;
/** the offset into mElement where the children of mElement are split.<BR>
* mOffset is the index of the first child in the right node.
* -1 means the new node gets no children.
*/
PRInt32 mOffset;
/** the element we create when splitting mElement */
nsCOMPtr<nsIDOMNode> mNewLeftNode;
/** the parent shared by mExistingRightNode and mNewLeftNode */
nsCOMPtr<nsIDOMNode> mParent;
nsIEditor* mEditor;
friend class TransactionFactory;
};
#endif

View File

@@ -0,0 +1,250 @@
/* -*- Mode: C++ tab-width: 2 indent-tabs-mode: nil c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL") you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include <stdio.h>
#include "nsIEditor.h"
#include "TextEditorTest.h"
#include "nsIDOMSelection.h"
#include "nsIDOMCharacterData.h"
#include "nsIDOMDocument.h"
#include "nsIDOMNode.h"
#include "nsIDOMNodeList.h"
#include "nsIEditProperty.h"
#include "nsString.h"
#ifdef NS_DEBUG
#define TEST_RESULT(r) { if (NS_FAILED(r)) {printf("FAILURE result=%X\n", r); return r; } }
#define TEST_POINTER(p) { if (!p) {printf("FAILURE null pointer\n"); return NS_ERROR_NULL_POINTER; } }
TextEditorTest::TextEditorTest()
{
printf("constructed a TextEditorTest\n");
}
TextEditorTest::~TextEditorTest()
{
printf("destroyed a TextEditorTest\n");
}
void TextEditorTest::Run(nsIEditor *aEditor, PRInt32 *outNumTests, PRInt32 *outNumTestsFailed)
{
if (!aEditor) return;
mTextEditor = do_QueryInterface(aEditor);
mEditor = do_QueryInterface(aEditor);
RunUnitTest(outNumTests, outNumTestsFailed);
}
nsresult TextEditorTest::RunUnitTest(PRInt32 *outNumTests, PRInt32 *outNumTestsFailed)
{
nsresult result;
if (!outNumTests || !outNumTestsFailed)
return NS_ERROR_NULL_POINTER;
*outNumTests = 0;
*outNumTestsFailed = 0;
result = InitDoc();
TEST_RESULT(result);
// shouldn't we just bail on error here?
// insert some simple text
nsString docContent("1234567890abcdefghij1234567890");
result = mTextEditor->InsertText(docContent);
TEST_RESULT(result);
(*outNumTests)++;
(*outNumTestsFailed) += (NS_FAILED(result) != NS_OK);
// insert some more text
nsString docContent2("Moreover, I am cognizant of the interrelatedness of all communities and states. I cannot sit idly by in Atlanta and not be concerned about what happens in Birmingham. Injustice anywhere is a threat to justice everywhere");
result = mTextEditor->InsertText(docContent2);
TEST_RESULT(result);
(*outNumTests)++;
(*outNumTestsFailed) += (NS_FAILED(result) != NS_OK);
result = TestInsertBreak();
TEST_RESULT(result);
(*outNumTests)++;
(*outNumTestsFailed) += (NS_FAILED(result) != NS_OK);
result = TestTextProperties();
TEST_RESULT(result);
(*outNumTests)++;
(*outNumTestsFailed) += (NS_FAILED(result) != NS_OK);
// get us back to the original document
result = mEditor->Undo(12);
TEST_RESULT(result);
return result;
}
nsresult TextEditorTest::InitDoc()
{
nsresult result = mEditor->SelectAll();
TEST_RESULT(result);
result = mEditor->DeleteSelection(nsIEditor::eDeleteNext);
TEST_RESULT(result);
return result;
}
nsresult TextEditorTest::TestInsertBreak()
{
nsCOMPtr<nsIDOMSelection>selection;
nsresult result = mEditor->GetSelection(getter_AddRefs(selection));
TEST_RESULT(result);
TEST_POINTER(selection.get());
nsCOMPtr<nsIDOMNode>anchor;
result = selection->GetAnchorNode(getter_AddRefs(anchor));
TEST_RESULT(result);
TEST_POINTER(anchor.get());
selection->Collapse(anchor, 0);
// insert one break
printf("inserting a break\n");
result = mTextEditor->InsertBreak();
TEST_RESULT(result);
mEditor->DebugDumpContent();
// insert a second break adjacent to the first
printf("inserting a second break\n");
result = mTextEditor->InsertBreak();
TEST_RESULT(result);
mEditor->DebugDumpContent();
return result;
}
nsresult TextEditorTest::TestTextProperties()
{
nsCOMPtr<nsIDOMDocument>doc;
nsresult result = mEditor->GetDocument(getter_AddRefs(doc));
TEST_RESULT(result);
TEST_POINTER(doc.get());
nsCOMPtr<nsIDOMNodeList>nodeList;
nsAutoString textTag = "__moz_text";
result = doc->GetElementsByTagName(textTag, getter_AddRefs(nodeList));
TEST_RESULT(result);
TEST_POINTER(nodeList.get());
PRUint32 count;
nodeList->GetLength(&count);
NS_ASSERTION(0!=count, "there are no text nodes in the document!");
nsCOMPtr<nsIDOMNode>textNode;
result = nodeList->Item(count-1, getter_AddRefs(textNode));
TEST_RESULT(result);
TEST_POINTER(textNode.get());
// set the whole text node to bold
printf("set the whole first text node to bold\n");
nsCOMPtr<nsIDOMSelection>selection;
result = mEditor->GetSelection(getter_AddRefs(selection));
TEST_RESULT(result);
TEST_POINTER(selection.get());
nsCOMPtr<nsIDOMCharacterData>textData;
textData = do_QueryInterface(textNode);
PRUint32 length;
textData->GetLength(&length);
selection->Collapse(textNode, 0);
selection->Extend(textNode, length);
PRBool any = PR_FALSE;
PRBool all = PR_FALSE;
PRBool first=PR_FALSE;
result = mTextEditor->GetInlineProperty(nsIEditProperty::b, nsnull, nsnull, first, any, all);
TEST_RESULT(result);
NS_ASSERTION(PR_FALSE==first, "first should be false");
NS_ASSERTION(PR_FALSE==any, "any should be false");
NS_ASSERTION(PR_FALSE==all, "all should be false");
result = mTextEditor->SetInlineProperty(nsIEditProperty::b, nsnull, nsnull);
TEST_RESULT(result);
result = mTextEditor->GetInlineProperty(nsIEditProperty::b, nsnull, nsnull, first, any, all);
TEST_RESULT(result);
NS_ASSERTION(PR_TRUE==first, "first should be true");
NS_ASSERTION(PR_TRUE==any, "any should be true");
NS_ASSERTION(PR_TRUE==all, "all should be true");
mEditor->DebugDumpContent();
// remove the bold we just set
printf("set the whole first text node to not bold\n");
result = mTextEditor->RemoveInlineProperty(nsIEditProperty::b, nsnull);
TEST_RESULT(result);
result = mTextEditor->GetInlineProperty(nsIEditProperty::b, nsnull, nsnull, first, any, all);
TEST_RESULT(result);
NS_ASSERTION(PR_FALSE==first, "first should be false");
NS_ASSERTION(PR_FALSE==any, "any should be false");
NS_ASSERTION(PR_FALSE==all, "all should be false");
mEditor->DebugDumpContent();
// set all but the first and last character to bold
printf("set the first text node (1, length-1) to bold and italic, and (2, length-1) to underline.\n");
selection->Collapse(textNode, 1);
selection->Extend(textNode, length-1);
result = mTextEditor->SetInlineProperty(nsIEditProperty::b, nsnull, nsnull);
TEST_RESULT(result);
result = mTextEditor->GetInlineProperty(nsIEditProperty::b, nsnull, nsnull, first, any, all);
TEST_RESULT(result);
NS_ASSERTION(PR_TRUE==first, "first should be true");
NS_ASSERTION(PR_TRUE==any, "any should be true");
NS_ASSERTION(PR_TRUE==all, "all should be true");
mEditor->DebugDumpContent();
// make all that same text italic
result = mTextEditor->SetInlineProperty(nsIEditProperty::i, nsnull, nsnull);
TEST_RESULT(result);
result = mTextEditor->GetInlineProperty(nsIEditProperty::i, nsnull, nsnull, first, any, all);
TEST_RESULT(result);
NS_ASSERTION(PR_TRUE==first, "first should be true");
NS_ASSERTION(PR_TRUE==any, "any should be true");
NS_ASSERTION(PR_TRUE==all, "all should be true");
result = mTextEditor->GetInlineProperty(nsIEditProperty::b, nsnull, nsnull, first, any, all);
TEST_RESULT(result);
NS_ASSERTION(PR_TRUE==first, "first should be true");
NS_ASSERTION(PR_TRUE==any, "any should be true");
NS_ASSERTION(PR_TRUE==all, "all should be true");
mEditor->DebugDumpContent();
// make all the text underlined, except for the first 2 and last 2 characters
result = doc->GetElementsByTagName(textTag, getter_AddRefs(nodeList));
TEST_RESULT(result);
TEST_POINTER(nodeList.get());
nodeList->GetLength(&count);
NS_ASSERTION(0!=count, "there are no text nodes in the document!");
result = nodeList->Item(count-2, getter_AddRefs(textNode));
TEST_RESULT(result);
TEST_POINTER(textNode.get());
textData = do_QueryInterface(textNode);
textData->GetLength(&length);
NS_ASSERTION(length==249, "wrong text node");
selection->Collapse(textNode, 1);
selection->Extend(textNode, length-2);
result = mTextEditor->SetInlineProperty(nsIEditProperty::u, nsnull, nsnull);
TEST_RESULT(result);
result = mTextEditor->GetInlineProperty(nsIEditProperty::u, nsnull, nsnull, first, any, all);
TEST_RESULT(result);
NS_ASSERTION(PR_TRUE==first, "first should be true");
NS_ASSERTION(PR_TRUE==any, "any should be true");
NS_ASSERTION(PR_TRUE==all, "all should be true");
mEditor->DebugDumpContent();
return result;
}
#endif

View File

@@ -0,0 +1,53 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef __TextEditorTest_h__
#define __TextEditorTest_h__
#ifdef NS_DEBUG
#include "nsCOMPtr.h"
#include "nsIEditor.h"
#include "nsIHighLevelHTMLEditor.h"
class TextEditorTest
{
public:
void Run(nsIEditor *aEditor, PRInt32 *outNumTests, PRInt32 *outNumTestsFailed);
TextEditorTest();
~TextEditorTest();
protected:
/** create an empty document */
nsresult InitDoc();
nsresult RunUnitTest(PRInt32 *outNumTests, PRInt32 *outNumTestsFailed);
nsresult TestInsertBreak();
nsresult TestTextProperties();
nsCOMPtr<nsIHighLevelHTMLEditor> mTextEditor;
nsCOMPtr<nsIEditor> mEditor;
};
#endif /* NS_DEBUG */
#endif

View File

@@ -0,0 +1,94 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "TransactionFactory.h"
// transactions this factory knows how to build
#include "EditAggregateTxn.h"
#include "PlaceholderTxn.h"
#include "InsertTextTxn.h"
#include "DeleteTextTxn.h"
#include "CreateElementTxn.h"
#include "InsertElementTxn.h"
#include "nsInsertHTMLTxn.h"
#include "DeleteElementTxn.h"
#include "DeleteRangeTxn.h"
#include "ChangeAttributeTxn.h"
#include "SplitElementTxn.h"
#include "JoinElementTxn.h"
#include "nsStyleSheetTxns.h"
#include "IMETextTxn.h"
#include "IMECommitTxn.h"
TransactionFactory::TransactionFactory()
{
}
TransactionFactory::~TransactionFactory()
{
}
nsresult
TransactionFactory::GetNewTransaction(REFNSIID aTxnType, EditTxn **aResult)
{
nsresult result = NS_OK;
*aResult = nsnull;
if (aTxnType.Equals(InsertTextTxn::GetCID()))
*aResult = new InsertTextTxn();
else if (aTxnType.Equals(DeleteTextTxn::GetCID()))
*aResult = new DeleteTextTxn();
else if (aTxnType.Equals(CreateElementTxn::GetCID()))
*aResult = new CreateElementTxn();
else if (aTxnType.Equals(InsertElementTxn::GetCID()))
*aResult = new InsertElementTxn();
else if (aTxnType.Equals(nsInsertHTMLTxn::GetCID()))
*aResult = new nsInsertHTMLTxn();
else if (aTxnType.Equals(DeleteElementTxn::GetCID()))
*aResult = new DeleteElementTxn();
else if (aTxnType.Equals(DeleteRangeTxn::GetCID()))
*aResult = new DeleteRangeTxn();
else if (aTxnType.Equals(ChangeAttributeTxn::GetCID()))
*aResult = new ChangeAttributeTxn();
else if (aTxnType.Equals(SplitElementTxn::GetCID()))
*aResult = new SplitElementTxn();
else if (aTxnType.Equals(JoinElementTxn::GetCID()))
*aResult = new JoinElementTxn();
else if (aTxnType.Equals(EditAggregateTxn::GetCID()))
*aResult = new EditAggregateTxn();
else if (aTxnType.Equals(IMETextTxn::GetCID()))
*aResult = new IMETextTxn();
else if (aTxnType.Equals(IMECommitTxn::GetCID()))
*aResult = new IMECommitTxn();
else if (aTxnType.Equals(AddStyleSheetTxn::GetCID()))
*aResult = new AddStyleSheetTxn();
else if (aTxnType.Equals(RemoveStyleSheetTxn::GetCID()))
*aResult = new RemoveStyleSheetTxn();
else if (aTxnType.Equals(PlaceholderTxn::GetCID()))
*aResult = new PlaceholderTxn();
else
result = NS_ERROR_NO_INTERFACE;
if (NS_SUCCEEDED(result) && nsnull==*aResult)
result = NS_ERROR_OUT_OF_MEMORY;
if (NS_SUCCEEDED(result))
NS_ADDREF(*aResult);
return result;
}

View File

@@ -0,0 +1,45 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef TransactionFactory_h__
#define TransactionFactory_h__
#include "nsISupports.h"
class EditTxn;
/**
* This class instantiates and optionally recycles edit transactions
* A recycler would be a separate static object, since this class does not get instantiated
*/
class TransactionFactory
{
protected:
TransactionFactory();
virtual ~TransactionFactory();
public:
/** return a transaction object of aTxnType, refcounted
* @return NS_ERROR_NO_INTERFACE if aTxnType is unknown,
* NS_ERROR_OUT_OF_MEMORY if the allocations fails.
*/
static nsresult GetNewTransaction(REFNSIID aTxnType, EditTxn **aResult);
};
#endif

View File

@@ -0,0 +1,54 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "TypeInState.h"
NS_IMPL_ADDREF(TypeInState)
NS_IMPL_RELEASE(TypeInState)
NS_IMETHODIMP
TypeInState::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(nsCOMTypeInfo<nsISupports>::GetIID())) {
*aInstancePtr = (void*)(nsISupports*)this;
NS_ADDREF_THIS();
return NS_OK;
}
if (aIID.Equals(nsIDOMSelectionListener::GetIID())) {
*aInstancePtr = (void*)(nsIDOMSelectionListener*)this;
NS_ADDREF_THIS();
return NS_OK;
}
return NS_NOINTERFACE;
}
TypeInState::~TypeInState()
{
};
NS_IMETHODIMP TypeInState::NotifySelectionChanged()
{
Reset();
return NS_OK;
};

View File

@@ -0,0 +1,232 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef TypeInState_h__
#define TypeInState_h__
#include "nsIDOMSelectionListener.h"
#include "nsIEditProperty.h"
class TypeInState : public nsIDOMSelectionListener
{
public:
NS_DECL_ISUPPORTS
TypeInState();
void Reset();
virtual ~TypeInState();
NS_IMETHOD NotifySelectionChanged();
void GetEnumForName(nsIAtom *aPropName, PRUint32 &aEnum);
void SetProp(PRUint32 aProp, PRBool aSet);
void SetPropValue(PRUint32 aProp, const nsString &aValue);
PRBool IsSet(PRUint32 aStyle);
PRBool IsAnySet();
void UnSet(PRUint32 aStyle);
void SetBold(PRBool aIsSet);
PRBool GetBold();
void SetItalic(PRBool aIsSet);
PRBool GetItalic();
void SetUnderline(PRBool aIsSet);
PRBool GetUnderline();
void SetFontFace(const nsString &aFace);
void GetFontFace(nsString &aFace);
void SetFontColor(const nsString &aColor);
void GetFontColor(nsString &aColor);
void SetFontSize(const nsString &aSize);
void GetFontSize(nsString &aSize);
protected:
PRBool mBold;
PRBool mItalic;
PRBool mUnderline;
nsString mFontFace;
nsString mFontColor;
nsString mFontSize;
PRUint32 mIsSet;
};
#define NS_TYPEINSTATE_UNKNOWN 0x00000000
#define NS_TYPEINSTATE_BOLD 0x00000001
#define NS_TYPEINSTATE_ITALIC 0x00000002
#define NS_TYPEINSTATE_UNDERLINE 0x00000004
#define NS_TYPEINSTATE_FONTFACE 0x00000008
#define NS_TYPEINSTATE_FONTCOLOR 0x00000010
#define NS_TYPEINSTATE_FONTSIZE 0x00000020
/* ----- inline method definitions ----- */
inline
void TypeInState::Reset()
{
mBold = PR_FALSE;
mItalic = PR_FALSE;
mUnderline = PR_FALSE;
mIsSet = 0;
};
inline
TypeInState::TypeInState()
{
NS_INIT_REFCNT();
Reset();
};
inline
void TypeInState::GetEnumForName(nsIAtom *aPropName, PRUint32 &aEnum)
{
aEnum = NS_TYPEINSTATE_UNKNOWN;
if (nsIEditProperty::b==aPropName) { aEnum = NS_TYPEINSTATE_BOLD; }
else if (nsIEditProperty::i==aPropName) { aEnum = NS_TYPEINSTATE_ITALIC; }
else if (nsIEditProperty::u==aPropName) { aEnum = NS_TYPEINSTATE_UNDERLINE; }
else if (nsIEditProperty::face==aPropName) { aEnum = NS_TYPEINSTATE_FONTFACE; }
else if (nsIEditProperty::color==aPropName) { aEnum = NS_TYPEINSTATE_FONTCOLOR; }
else if (nsIEditProperty::size==aPropName) { aEnum = NS_TYPEINSTATE_FONTSIZE; }
}
inline
PRBool TypeInState::IsSet(PRUint32 aStyle)
{
if ((PRBool)(mIsSet & aStyle))
return PR_TRUE;
else
return PR_FALSE;
};
inline
void TypeInState::UnSet(PRUint32 aStyle)
{
mIsSet &= ~aStyle;
};
inline
PRBool TypeInState::IsAnySet()
{
return (PRBool)(0!=mIsSet);
}
inline
void TypeInState::SetBold(PRBool aIsSet)
{
mBold = aIsSet;
mIsSet |= NS_TYPEINSTATE_BOLD;
};
inline
PRBool TypeInState::GetBold()
{ return mBold;};
inline
void TypeInState::SetItalic(PRBool aIsSet)
{
mItalic = aIsSet;
mIsSet |= NS_TYPEINSTATE_ITALIC;
};
inline
PRBool TypeInState::GetItalic()
{ return mItalic; };
inline
void TypeInState::SetUnderline(PRBool aIsSet)
{
mUnderline = aIsSet;
mIsSet |= NS_TYPEINSTATE_UNDERLINE;
};
inline
PRBool TypeInState::GetUnderline()
{ return mUnderline; };
inline
void TypeInState::SetFontFace(const nsString &aFace)
{
mFontFace = aFace;
mIsSet |= NS_TYPEINSTATE_FONTFACE;
};
inline
void TypeInState::GetFontFace(nsString &aFace)
{ aFace = mFontFace; };
inline
void TypeInState::SetFontColor(const nsString &aColor)
{
mFontColor = aColor;
mIsSet |= NS_TYPEINSTATE_FONTCOLOR;
};
inline
void TypeInState::GetFontColor(nsString &aColor)
{ aColor = mFontColor; };
inline
void TypeInState::SetFontSize(const nsString &aSize)
{
mFontSize = aSize;
mIsSet |= NS_TYPEINSTATE_FONTSIZE;
};
inline
void TypeInState::GetFontSize(nsString &aSize)
{ aSize = mFontSize; };
inline void TypeInState::SetProp(PRUint32 aProp, PRBool aSet)
{
switch (aProp)
{
case NS_TYPEINSTATE_BOLD:
SetBold(aSet);
break;
case NS_TYPEINSTATE_ITALIC:
SetItalic(aSet);
break;
case NS_TYPEINSTATE_UNDERLINE:
SetUnderline(aSet);
break;
}
}
inline void TypeInState::SetPropValue(PRUint32 aProp, const nsString &aValue)
{
switch (aProp)
{
case NS_TYPEINSTATE_FONTFACE:
SetFontFace(aValue);
break;
case NS_TYPEINSTATE_FONTCOLOR:
SetFontColor(aValue);
break;
case NS_TYPEINSTATE_FONTSIZE:
SetFontSize(aValue);
break;
}
}
#endif // TypeInState_h__

View File

@@ -0,0 +1,150 @@
#!nmake
#
# The contents of this file are subject to the Netscape Public License
# Version 1.0 (the "NPL"); you may not use this file except in
# compliance with the NPL. You may obtain a copy of the NPL at
# http://www.mozilla.org/NPL/
#
# Software distributed under the NPL is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
# for the specific language governing rights and limitations under the
# NPL.
#
# The Initial Developer of this code under the NPL is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All Rights
# Reserved.
DEPTH=..\..
IGNORE_MANIFEST=1
include <$(DEPTH)/config/config.mak>
LIBRARY_NAME=ender
CPPSRCS = \
nsInsertHTMLTxn.cpp \
nsEditor.cpp \
nsEditorUtils.cpp \
nsEditorRegistration.cpp \
nsTextEditRules.cpp \
nsHTMLEditRules.cpp \
TextEditorTest.cpp \
nsEditorEventListeners.cpp \
nsEditProperty.cpp \
nsEditorFactory.cpp \
EditTxn.cpp \
EditAggregateTxn.cpp \
ChangeAttributeTxn.cpp \
InsertTextTxn.cpp \
DeleteTextTxn.cpp \
PlaceholderTxn.cpp \
CreateElementTxn.cpp \
InsertElementTxn.cpp \
DeleteElementTxn.cpp \
DeleteRangeTxn.cpp \
SplitElementTxn.cpp \
JoinElementTxn.cpp \
nsStyleSheetTxns.cpp \
TransactionFactory.cpp \
TypeInState.cpp \
nsHTMLEditor.cpp \
EditTable.cpp \
nsInternetCiter.cpp \
nsAOLCiter.cpp \
nsInterfaceState.cpp \
nsEditorShell.cpp \
nsEditorShellFactory.cpp \
IMETextTxn.cpp \
IMECommitTxn.cpp \
$(NULL)
CPP_OBJS = \
.\$(OBJDIR)\nsInsertHTMLTxn.obj \
.\$(OBJDIR)\nsEditor.obj \
.\$(OBJDIR)\nsEditorUtils.obj \
.\$(OBJDIR)\nsEditorRegistration.obj \
.\$(OBJDIR)\nsTextEditRules.obj \
.\$(OBJDIR)\TextEditorTest.obj \
.\$(OBJDIR)\nsHTMLEditRules.obj \
.\$(OBJDIR)\nsEditorEventListeners.obj \
.\$(OBJDIR)\nsEditProperty.obj \
.\$(OBJDIR)\nsEditorFactory.obj \
.\$(OBJDIR)\EditTxn.obj \
.\$(OBJDIR)\EditAggregateTxn.obj \
.\$(OBJDIR)\ChangeAttributeTxn.obj \
.\$(OBJDIR)\InsertTextTxn.obj \
.\$(OBJDIR)\DeleteTextTxn.obj \
.\$(OBJDIR)\PlaceholderTxn.obj \
.\$(OBJDIR)\CreateElementTxn.obj \
.\$(OBJDIR)\InsertElementTxn.obj \
.\$(OBJDIR)\DeleteElementTxn.obj \
.\$(OBJDIR)\DeleteRangeTxn.obj \
.\$(OBJDIR)\SplitElementTxn.obj \
.\$(OBJDIR)\JoinElementTxn.obj \
.\$(OBJDIR)\nsStyleSheetTxns.obj \
.\$(OBJDIR)\TransactionFactory.obj \
.\$(OBJDIR)\TypeInState.obj \
.\$(OBJDIR)\nsHTMLEditor.obj \
.\$(OBJDIR)\EditTable.obj \
.\$(OBJDIR)\nsInternetCiter.obj \
.\$(OBJDIR)\nsAOLCiter.obj \
.\$(OBJDIR)\nsInterfaceState.obj \
.\$(OBJDIR)\nsEditorShell.obj \
.\$(OBJDIR)\nsEditorShellFactory.obj \
.\$(OBJDIR)\nsJSEditorLog.obj \
.\$(OBJDIR)\nsJSTxnLog.obj \
.\$(OBJDIR)\IMETextTxn.obj \
.\$(OBJDIR)\IMECommitTxn.obj \
$(NULL)
MODULE=editor
MAKE_OBJ_TYPE = DLL
DLLNAME = ender
DLL=.\$(OBJDIR)\$(DLLNAME).dll
!if defined(ENABLE_JS_EDITOR_LOG)
CPPSRCS += \
nsJSEditorLog.cpp \
nsJSTxnLog.cpp \
$(NULL)
CPP_OBJS += \
.\$(OBJDIR)\nsJSEditorLog.obj \
.\$(OBJDIR)\nsJSTxnLog.obj \
$(NULL)
DEFINES = -DENABLE_JS_EDITOR_LOG $(DEFINES)
!endif
LCFLAGS = \
$(LCFLAGS) \
$(DEFINES) \
$(NULL)
# These are the libraries we need to link with to create the dll
LLIBS= \
$(DIST)\lib\xpcom.lib \
$(DIST)\lib\raptorhtmlpars.lib \
$(DIST)\lib\raptorwidget_s.lib \
!ifdef NECKO
$(DIST)\lib\neckoutil_s.lib \
!else
$(DIST)\lib\netlib.lib \
!endif
$(LIBNSPR)
!if "$(MOZ_BITS)"=="32" && defined(MOZ_DEBUG) && defined(GLOWCODE)
LLIBS=$(LLIBS) $(GLOWDIR)\glowcode.lib
!endif
include <$(DEPTH)\config\rules.mak>
install:: $(DLL)
$(MAKE_INSTALL) .\$(OBJDIR)\$(DLLNAME).dll $(DIST)\bin\components
$(MAKE_INSTALL) .\$(OBJDIR)\$(DLLNAME).lib $(DIST)\lib
clobber::
rm -f $(DIST)\bin\components\$(DLLNAME).dll
rm -f $(DIST)\lib\$(DLLNAME).lib

View File

@@ -0,0 +1,82 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsAOLCiter.h"
#include "nsString.h"
/** Mail citations using the AOL style >> This is a citation <<
*/
nsAOLCiter::nsAOLCiter()
{
}
nsAOLCiter::~nsAOLCiter()
{
}
NS_IMPL_ADDREF(nsAOLCiter)
NS_IMPL_RELEASE(nsAOLCiter)
NS_IMETHODIMP
nsAOLCiter::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(nsCOMTypeInfo<nsISupports>::GetIID()))
{
*aInstancePtr = (void*)this;
NS_ADDREF_THIS();
return NS_OK;
}
if (aIID.Equals(nsICiter::GetIID())) {
*aInstancePtr = (void*)(nsICiter*)this;
NS_ADDREF_THIS();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMETHODIMP
nsAOLCiter::GetCiteString(const nsString& aInString, nsString& aOutString)
{
aOutString = "\n\n>> ";
aOutString += aInString;
// See if the last char is a newline, and replace it if so
PRUnichar newline ('\n');
if (aOutString.Last() == newline)
{
aOutString.SetCharAt(' ',aOutString.Length());
aOutString += "<<\n";
}
else
{
aOutString += " <<\n";
}
return NS_OK;
}

View File

@@ -0,0 +1,41 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsAOLCiter_h__
#define nsAOLCiter_h__
#include "nsICiter.h"
#include "nsString.h"
/** Mail citations using the AOL style >> This is a citation <<
*/
class nsAOLCiter : public nsICiter
{
public:
nsAOLCiter();
virtual ~nsAOLCiter();
//Interfaces for addref and release and queryinterface
//NOTE: Use NS_DECL_ISUPPORTS_INHERITED in any class inherited from nsEditor
NS_DECL_ISUPPORTS
NS_IMETHOD GetCiteString(const nsString& aInString, nsString& aOutString);
};
#endif //nsAOLCiter_h__

View File

@@ -0,0 +1,131 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsEditFactory.h"
#include "nsIEditor.h"
#include "nsEditor.h"
#include "nsEditorCID.h"
#include "nsIComponentManager.h"
static NS_DEFINE_IID(kIEditFactoryIID, NS_IEDITORFACTORY_IID);
static NS_DEFINE_CID(kEditorCID, NS_EDITOR_CID);
nsresult
GetEditFactory(nsIFactory **aFactory, const nsCID & aClass)
{
// XXX Note static which never gets released, even on library unload.
// XXX Was an nsCOMPtr but that caused a crash on exit,
// XXX http://bugzilla.mozilla.org/show_bug.cgi?id=7938
PR_EnterMonitor(GetEditorMonitor());
nsEditFactory *factory = new nsEditFactory(aClass);
if (!factory)
return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsIFactory> pNSIFactory = do_QueryInterface(factory);
if (!pNSIFactory)
return NS_ERROR_NO_INTERFACE;
nsresult result = pNSIFactory->QueryInterface(nsIFactory::GetIID(),
(void **)aFactory);
PR_ExitMonitor(GetEditorMonitor());
return result;
}
////////////////////////////////////////////////////////////////////////////
// from nsISupports
NS_METHOD
nsEditFactory::QueryInterface(const nsIID& aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
NS_NOTREACHED("!nsEditor");
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(nsIFactory::GetIID()) ||
aIID.Equals(nsCOMTypeInfo<nsISupports>::GetIID())) {
*aInstancePtr = (void*) this;
AddRef();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMPL_ADDREF(nsEditFactory)
NS_IMPL_RELEASE(nsEditFactory)
////////////////////////////////////////////////////////////////////////////
// from nsIFactory:
NS_METHOD
nsEditFactory::CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
*aResult = nsnull;
nsISupports *obj = nsnull;
if (!aResult)
return NS_ERROR_NULL_POINTER;
if (aOuter && !aIID.Equals(nsCOMTypeInfo<nsISupports>::GetIID()))
return NS_NOINTERFACE; // XXX right error?
if (mCID.Equals(kEditorCID))
obj = (nsISupports *)(nsIEditor*)new nsEditor();
//more class ids to support. here
if (obj && NS_FAILED(obj->QueryInterface(aIID, (void**)aResult)) )
{
delete obj;
return NS_NOINTERFACE;
}
return NS_OK;
}
NS_METHOD
nsEditFactory::LockFactory(PRBool aLock)
{
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////
// from nsEditFactory:
nsEditFactory::nsEditFactory(const nsCID &aClass)
:mCID(aClass)
{
NS_INIT_REFCNT();
}
nsEditFactory::~nsEditFactory()
{
//nsComponentManager::UnregisterFactory(mCID, (nsIFactory *)this); //we are out of ref counts anyway
}

View File

@@ -0,0 +1,67 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIEditFactory_h___
#define nsIEditFactory_h___
#include "nsISupports.h"
#include "nsIFactory.h"
/*
EditFactory that can make an editor
*/
/**
* This supplies the neccessary entrance to the edit module. it will return any
* instantiations that we need.
*/
class nsEditFactory;
nsresult GetEditFactory(nsIFactory **aFactory, const nsCID & aClass);
class nsEditFactory : public nsIFactory {
public:
////////////////////////////////////////////////////////////////////////////
// from nsISupports and AggregatedQueryInterface:
NS_DECL_ISUPPORTS
////////////////////////////////////////////////////////////////////////////
// from nsIFactory:
NS_IMETHOD
CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult);
NS_IMETHOD
LockFactory(PRBool aLock);
////////////////////////////////////////////////////////////////////////////
// from nsEditFactory:
virtual ~nsEditFactory(void);
private:
nsEditFactory(const nsCID &aClass); //will fill the aFactory with the result from queryinterface
/** getEditFactory
* creates an edit factory other CSID supported friend functions here.
*/
friend nsresult GetEditFactory(nsIFactory **, const nsCID & );
const nsCID &mCID;
};
#endif //nsIEditFactory_h___

View File

@@ -0,0 +1,326 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsEditProperty.h"
#include "nsString.h"
// singleton instance
static nsEditProperty *gInstance;
NS_IMPL_ADDREF(nsEditProperty)
NS_IMPL_RELEASE(nsEditProperty)
// XXX: remove when html atoms are exported from layout
// inline tags
nsIAtom * nsIEditProperty::b;
nsIAtom * nsIEditProperty::big;
nsIAtom * nsIEditProperty::i;
nsIAtom * nsIEditProperty::small;
nsIAtom * nsIEditProperty::strike;
nsIAtom * nsIEditProperty::sub;
nsIAtom * nsIEditProperty::sup;
nsIAtom * nsIEditProperty::tt;
nsIAtom * nsIEditProperty::u;
nsIAtom * nsIEditProperty::em;
nsIAtom * nsIEditProperty::strong;
nsIAtom * nsIEditProperty::dfn;
nsIAtom * nsIEditProperty::code;
nsIAtom * nsIEditProperty::samp;
nsIAtom * nsIEditProperty::kbd;
nsIAtom * nsIEditProperty::var;
nsIAtom * nsIEditProperty::cite;
nsIAtom * nsIEditProperty::abbr;
nsIAtom * nsIEditProperty::acronym;
nsIAtom * nsIEditProperty::font;
nsIAtom * nsIEditProperty::a;
nsIAtom * nsIEditProperty::img;
nsIAtom * nsIEditProperty::object;
nsIAtom * nsIEditProperty::br;
nsIAtom * nsIEditProperty::script;
nsIAtom * nsIEditProperty::map;
nsIAtom * nsIEditProperty::q;
nsIAtom * nsIEditProperty::span;
nsIAtom * nsIEditProperty::bdo;
nsIAtom * nsIEditProperty::input;
nsIAtom * nsIEditProperty::select;
nsIAtom * nsIEditProperty::textarea;
nsIAtom * nsIEditProperty::label;
nsIAtom * nsIEditProperty::button;
nsIAtom * nsIEditProperty::p;
nsIAtom * nsIEditProperty::div;
nsIAtom * nsIEditProperty::blockquote;
nsIAtom * nsIEditProperty::h1;
nsIAtom * nsIEditProperty::h2;
nsIAtom * nsIEditProperty::h3;
nsIAtom * nsIEditProperty::h4;
nsIAtom * nsIEditProperty::h5;
nsIAtom * nsIEditProperty::h6;
nsIAtom * nsIEditProperty::ul;
nsIAtom * nsIEditProperty::ol;
nsIAtom * nsIEditProperty::dl;
nsIAtom * nsIEditProperty::pre;
nsIAtom * nsIEditProperty::noscript;
nsIAtom * nsIEditProperty::form;
nsIAtom * nsIEditProperty::hr;
nsIAtom * nsIEditProperty::table;
nsIAtom * nsIEditProperty::fieldset;
nsIAtom * nsIEditProperty::address;
nsIAtom * nsIEditProperty::body;
nsIAtom * nsIEditProperty::tr;
nsIAtom * nsIEditProperty::td;
nsIAtom * nsIEditProperty::th;
nsIAtom * nsIEditProperty::caption;
nsIAtom * nsIEditProperty::col;
nsIAtom * nsIEditProperty::colgroup;
nsIAtom * nsIEditProperty::thead;
nsIAtom * nsIEditProperty::tfoot;
nsIAtom * nsIEditProperty::li;
nsIAtom * nsIEditProperty::dt;
nsIAtom * nsIEditProperty::dd;
nsIAtom * nsIEditProperty::legend;
nsIAtom * nsIEditProperty::color;
nsIAtom * nsIEditProperty::face;
nsIAtom * nsIEditProperty::size;
// special
nsString * nsIEditProperty::allProperties;
/* From the HTML 4.0 DTD,
INLINE:
<!-- %inline; covers inline or "text-level" elements -->
<!ENTITY % inline "#PCDATA | %fontstyle; | %phrase; | %special; | %formctrl;">
<!ENTITY % fontstyle "TT | I | B | BIG | SMALL">
<!ENTITY % phrase "EM | STRONG | DFN | CODE |
SAMP | KBD | VAR | CITE | ABBR | ACRONYM" >
<!ENTITY % special
"A | IMG | OBJECT | BR | SCRIPT | MAP | Q | SUB | SUP | SPAN | BDO">
<!ENTITY % formctrl "INPUT | SELECT | TEXTAREA | LABEL | BUTTON">
BLOCK:
<!ENTITY % block
"P | %heading (h1-h6); | %list (UL | OL); | %preformatted (PRE); | DL | DIV | NOSCRIPT |
BLOCKQUOTE | FORM | HR | TABLE | FIELDSET | ADDRESS">
But what about BODY, TR, TD, TH, CAPTION, COL, COLGROUP, THEAD, TFOOT, LI, DT, DD, LEGEND, etc.?
*/
nsEditProperty::nsEditProperty()
{
NS_INIT_REFCNT();
// inline tags
nsIEditProperty::b = NS_NewAtom("b");
nsIEditProperty::big = NS_NewAtom("big");
nsIEditProperty::i = NS_NewAtom("i");
nsIEditProperty::small = NS_NewAtom("small");
nsIEditProperty::strike = NS_NewAtom("strike");
nsIEditProperty::sub = NS_NewAtom("sub");
nsIEditProperty::sup = NS_NewAtom("sup");
nsIEditProperty::tt = NS_NewAtom("tt");
nsIEditProperty::u = NS_NewAtom("u");
nsIEditProperty::em = NS_NewAtom("em");
nsIEditProperty::strong = NS_NewAtom("strong");
nsIEditProperty::dfn = NS_NewAtom("dfn");
nsIEditProperty::code = NS_NewAtom("code");
nsIEditProperty::samp = NS_NewAtom("samp");
nsIEditProperty::kbd = NS_NewAtom("kbd");
nsIEditProperty::var = NS_NewAtom("var");
nsIEditProperty::cite = NS_NewAtom("cite");
nsIEditProperty::abbr = NS_NewAtom("abbr");
nsIEditProperty::acronym = NS_NewAtom("acronym");
nsIEditProperty::font = NS_NewAtom("font");
nsIEditProperty::a = NS_NewAtom("a");
nsIEditProperty::img = NS_NewAtom("img");
nsIEditProperty::object = NS_NewAtom("object");
nsIEditProperty::br = NS_NewAtom("br");
nsIEditProperty::script = NS_NewAtom("script");
nsIEditProperty::map = NS_NewAtom("map");
nsIEditProperty::q = NS_NewAtom("q");
nsIEditProperty::span = NS_NewAtom("span");
nsIEditProperty::bdo = NS_NewAtom("bdo");
nsIEditProperty::input = NS_NewAtom("input");
nsIEditProperty::select = NS_NewAtom("select");
nsIEditProperty::textarea = NS_NewAtom("textarea");
nsIEditProperty::label = NS_NewAtom("label");
nsIEditProperty::button = NS_NewAtom("button");
// block tags
nsIEditProperty::p = NS_NewAtom("p");
nsIEditProperty::div = NS_NewAtom("div");
nsIEditProperty::blockquote = NS_NewAtom("blockquote");
nsIEditProperty::h1 = NS_NewAtom("h1");
nsIEditProperty::h2 = NS_NewAtom("h2");
nsIEditProperty::h3 = NS_NewAtom("h3");
nsIEditProperty::h4 = NS_NewAtom("h4");
nsIEditProperty::h5 = NS_NewAtom("h5");
nsIEditProperty::h6 = NS_NewAtom("h6");
nsIEditProperty::ul = NS_NewAtom("ul");
nsIEditProperty::ol = NS_NewAtom("ol");
nsIEditProperty::dl = NS_NewAtom("dl");
nsIEditProperty::pre = NS_NewAtom("pre");
nsIEditProperty::noscript = NS_NewAtom("noscript");
nsIEditProperty::form = NS_NewAtom("form");
nsIEditProperty::hr = NS_NewAtom("hr");
nsIEditProperty::table = NS_NewAtom("table");
nsIEditProperty::fieldset = NS_NewAtom("fieldset");
nsIEditProperty::address = NS_NewAtom("address");
// Unclear from
// DTD, block?
nsIEditProperty::body = NS_NewAtom("body");
nsIEditProperty::tr = NS_NewAtom("tr");
nsIEditProperty::td = NS_NewAtom("td");
nsIEditProperty::th = NS_NewAtom("th");
nsIEditProperty::caption = NS_NewAtom("caption");
nsIEditProperty::col = NS_NewAtom("col");
nsIEditProperty::colgroup = NS_NewAtom("colgroup");
nsIEditProperty::thead = NS_NewAtom("thead");
nsIEditProperty::tfoot = NS_NewAtom("tfoot");
nsIEditProperty::li = NS_NewAtom("li");
nsIEditProperty::dt = NS_NewAtom("dt");
nsIEditProperty::dd = NS_NewAtom("dd");
nsIEditProperty::legend = NS_NewAtom("legend");
// inline
// properties
nsIEditProperty::color = NS_NewAtom("color");
nsIEditProperty::face = NS_NewAtom("face");
nsIEditProperty::size = NS_NewAtom("size");
// special
nsIEditProperty::allProperties = new nsString("moz_allproperties");
}
nsEditProperty::~nsEditProperty()
{
NS_IF_RELEASE(nsIEditProperty::b);
NS_IF_RELEASE(nsIEditProperty::big);
NS_IF_RELEASE(nsIEditProperty::i);
NS_IF_RELEASE(nsIEditProperty::small);
NS_IF_RELEASE(nsIEditProperty::strike);
NS_IF_RELEASE(nsIEditProperty::sub);
NS_IF_RELEASE(nsIEditProperty::sup);
NS_IF_RELEASE(nsIEditProperty::tt);
NS_IF_RELEASE(nsIEditProperty::u);
NS_IF_RELEASE(nsIEditProperty::em);
NS_IF_RELEASE(nsIEditProperty::strong);
NS_IF_RELEASE(nsIEditProperty::dfn);
NS_IF_RELEASE(nsIEditProperty::code);
NS_IF_RELEASE(nsIEditProperty::samp);
NS_IF_RELEASE(nsIEditProperty::kbd);
NS_IF_RELEASE(nsIEditProperty::var);
NS_IF_RELEASE(nsIEditProperty::cite);
NS_IF_RELEASE(nsIEditProperty::abbr);
NS_IF_RELEASE(nsIEditProperty::acronym);
NS_IF_RELEASE(nsIEditProperty::font);
NS_IF_RELEASE(nsIEditProperty::a);
NS_IF_RELEASE(nsIEditProperty::img);
NS_IF_RELEASE(nsIEditProperty::object);
NS_IF_RELEASE(nsIEditProperty::br);
NS_IF_RELEASE(nsIEditProperty::script);
NS_IF_RELEASE(nsIEditProperty::map);
NS_IF_RELEASE(nsIEditProperty::q);
NS_IF_RELEASE(nsIEditProperty::span);
NS_IF_RELEASE(nsIEditProperty::bdo);
NS_IF_RELEASE(nsIEditProperty::input);
NS_IF_RELEASE(nsIEditProperty::select);
NS_IF_RELEASE(nsIEditProperty::textarea);
NS_IF_RELEASE(nsIEditProperty::label);
NS_IF_RELEASE(nsIEditProperty::button);
NS_IF_RELEASE(nsIEditProperty::p);
NS_IF_RELEASE(nsIEditProperty::div);
NS_IF_RELEASE(nsIEditProperty::blockquote);
NS_IF_RELEASE(nsIEditProperty::h1);
NS_IF_RELEASE(nsIEditProperty::h2);
NS_IF_RELEASE(nsIEditProperty::h3);
NS_IF_RELEASE(nsIEditProperty::h4);
NS_IF_RELEASE(nsIEditProperty::h5);
NS_IF_RELEASE(nsIEditProperty::h6);
NS_IF_RELEASE(nsIEditProperty::ul);
NS_IF_RELEASE(nsIEditProperty::ol);
NS_IF_RELEASE(nsIEditProperty::dl);
NS_IF_RELEASE(nsIEditProperty::pre);
NS_IF_RELEASE(nsIEditProperty::noscript);
NS_IF_RELEASE(nsIEditProperty::form);
NS_IF_RELEASE(nsIEditProperty::hr);
NS_IF_RELEASE(nsIEditProperty::table);
NS_IF_RELEASE(nsIEditProperty::fieldset);
NS_IF_RELEASE(nsIEditProperty::address);
NS_IF_RELEASE(nsIEditProperty::body);
NS_IF_RELEASE(nsIEditProperty::tr);
NS_IF_RELEASE(nsIEditProperty::td);
NS_IF_RELEASE(nsIEditProperty::th);
NS_IF_RELEASE(nsIEditProperty::caption);
NS_IF_RELEASE(nsIEditProperty::col);
NS_IF_RELEASE(nsIEditProperty::colgroup);
NS_IF_RELEASE(nsIEditProperty::thead);
NS_IF_RELEASE(nsIEditProperty::tfoot);
NS_IF_RELEASE(nsIEditProperty::li);
NS_IF_RELEASE(nsIEditProperty::dt);
NS_IF_RELEASE(nsIEditProperty::dd);
NS_IF_RELEASE(nsIEditProperty::legend);
NS_IF_RELEASE(nsIEditProperty::color);
NS_IF_RELEASE(nsIEditProperty::face);
NS_IF_RELEASE(nsIEditProperty::size);
// special
if (nsIEditProperty::allProperties) {
delete (nsIEditProperty::allProperties);
nsIEditProperty::allProperties = nsnull;
}
gInstance = nsnull;
}
NS_IMETHODIMP
nsEditProperty::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(nsCOMTypeInfo<nsISupports>::GetIID())) {
*aInstancePtr = (void*)(nsISupports*)this;
NS_ADDREF_THIS();
return NS_OK;
}
if (aIID.Equals(nsIEditProperty::GetIID())) {
*aInstancePtr = (void*)(nsIEditProperty*)this;
NS_ADDREF_THIS();
return NS_OK;
}
return NS_NOINTERFACE;
}
/* Factory for edit property object */
nsresult NS_NewEditProperty(nsIEditProperty **aResult)
{
if (aResult)
{
if (!gInstance)
{
gInstance = new nsEditProperty();
if (!gInstance) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
*aResult = gInstance;
NS_ADDREF(*aResult);
return NS_OK;
}
return NS_ERROR_NULL_POINTER;
}

View File

@@ -0,0 +1,45 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef __nsEditProperty_h__
#define __nsEditProperty_h__
#include "nsIEditProperty.h"
#include "nsIAtom.h"
#include "nsCOMPtr.h"
#include "nsISupports.h"
/** simple class for describing a single property as it relates to a range of content.
* not ref counted.
*
*/
class nsEditProperty : public nsIEditProperty
{
public:
/*interfaces for addref and release and queryinterface*/
NS_DECL_ISUPPORTS
protected:
nsEditProperty ();
virtual ~nsEditProperty();
friend nsresult NS_NewEditProperty(nsIEditProperty **aResult);
};
#endif

View File

@@ -0,0 +1,55 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsEditRules_h__
#define nsEditRules_h__
class nsHTMLEditor;
class nsIDOMSelection;
/***************************************************************************
* base for an object to encapsulate any additional info needed to be passed
* to rules system by the editor
*/
class nsRulesInfo
{
public:
nsRulesInfo(int aAction) : action(aAction) {}
virtual ~nsRulesInfo() {}
int action;
};
/***************************************************************************
* Interface of editing rules.
*
*/
class nsEditRules
{
public:
NS_IMETHOD Init(nsHTMLEditor *aEditor)=0;
NS_IMETHOD WillDoAction(nsIDOMSelection *aSelection, nsRulesInfo *aInfo, PRBool *aCancel)=0;
NS_IMETHOD DidDoAction(nsIDOMSelection *aSelection, nsRulesInfo *aInfo, nsresult aResult)=0;
NS_IMETHOD GetFlags(PRUint32 *aFlags)=0;
NS_IMETHOD SetFlags(PRUint32 aFlags)=0;
};
#endif //nsEditRules_h__

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,633 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef __editor_h__
#define __editor_h__
#include "nsCOMPtr.h"
#include "prmon.h"
#include "nsIEditor.h"
#include "nsIEditorIMESupport.h"
#include "nsIEditorLogging.h"
#include "nsIDOMDocument.h"
#include "nsIDOMSelection.h"
#include "nsIDOMCharacterData.h"
#include "nsIDOMEventListener.h"
#include "nsIDOMRange.h"
#include "nsIDOMTextRangeList.h"
#include "nsIStringBundle.h"
#include "nsITransactionManager.h"
#include "TransactionFactory.h"
#include "nsIComponentManager.h"
#include "nsISupportsArray.h"
#include "nsIEditProperty.h"
#include "nsIFileSpec.h"
#include "nsIDOMCharacterData.h"
#include "nsICSSStyleSheet.h"
#include "nsIDTD.h"
class nsIEditActionListener;
class nsIDocumentStateListener;
class nsIDOMCharacterData;
class nsIDOMRange;
class nsIPresShell;
class nsIViewManager;
class ChangeAttributeTxn;
class CreateElementTxn;
class InsertElementTxn;
class DeleteElementTxn;
class InsertTextTxn;
class DeleteTextTxn;
class SplitElementTxn;
class JoinElementTxn;
class EditAggregateTxn;
class nsVoidArray;
class nsISupportsArray;
class nsIPref;
class nsIStringBundleService;
class nsIStringBundle;
class nsILocale;
class IMETextTxn;
class AddStyleSheetTxn;
class RemoveStyleSheetTxn;
#ifdef ENABLE_JS_EDITOR_LOG
class nsJSEditorLog;
class nsJSTxnLog;
#endif // ENABLE_JS_EDITOR_LOG
//This is the monitor for the editor.
PRMonitor *GetEditorMonitor();
/** implementation of an editor object. it will be the controler/focal point
* for the main editor services. i.e. the GUIManager, publishing, transaction
* manager, event interfaces. the idea for the event interfaces is to have them
* delegate the actual commands to the editor independent of the XPFE implementation.
*/
class nsEditor : public nsIEditor,
public nsIEditorIMESupport,
public nsIEditorLogging
{
public:
enum IterDirection
{
kIterForward,
kIterBackward
};
static const char* kMOZEditorBogusNodeAttr;
static const char* kMOZEditorBogusNodeValue;
/** The default constructor. This should suffice. the setting of the interfaces is done
* after the construction of the editor class.
*/
nsEditor();
/** The default destructor. This should suffice. Should this be pure virtual
* for someone to derive from the nsEditor later? I dont believe so.
*/
virtual ~nsEditor();
//Interfaces for addref and release and queryinterface
//NOTE: Use NS_DECL_ISUPPORTS_INHERITED in any class inherited from nsEditor
NS_DECL_ISUPPORTS
/* ------------ nsIEditor methods -------------- */
NS_IMETHOD Init(nsIDOMDocument *aDoc, nsIPresShell *aPresShell, PRUint32 aFlags);
NS_IMETHOD PostCreate();
NS_IMETHOD GetFlags(PRUint32 *aFlags) = 0;
NS_IMETHOD SetFlags(PRUint32 aFlags) = 0;
NS_IMETHOD GetDocument(nsIDOMDocument **aDoc);
NS_IMETHOD GetPresShell(nsIPresShell **aPS);
NS_IMETHOD GetSelection(nsIDOMSelection **aSelection);
NS_IMETHOD EnableUndo(PRBool aEnable);
NS_IMETHOD Do(nsITransaction *aTxn);
NS_IMETHOD Undo(PRUint32 aCount);
NS_IMETHOD CanUndo(PRBool &aIsEnabled, PRBool &aCanUndo);
NS_IMETHOD Redo(PRUint32 aCount);
NS_IMETHOD CanRedo(PRBool &aIsEnabled, PRBool &aCanRedo);
NS_IMETHOD BeginTransaction();
NS_IMETHOD EndTransaction();
// file handling
NS_IMETHOD Save();
NS_IMETHOD SaveAs(PRBool aSavingCopy);
NS_IMETHOD GetDocumentModified(PRBool *outDocModified);
// these are pure virtual in this base class
NS_IMETHOD Cut() = 0;
NS_IMETHOD Copy() = 0;
NS_IMETHOD Paste() = 0;
NS_IMETHOD SelectAll();
NS_IMETHOD BeginningOfDocument();
NS_IMETHOD EndOfDocument();
/* Node and element manipulation */
NS_IMETHOD SetAttribute(nsIDOMElement * aElement,
const nsString& aAttribute,
const nsString& aValue);
NS_IMETHOD GetAttributeValue(nsIDOMElement * aElement,
const nsString& aAttribute,
nsString& aResultValue,
PRBool& aResultIsSet);
NS_IMETHOD RemoveAttribute(nsIDOMElement *aElement, const nsString& aAttribute);
NS_IMETHOD CreateNode(const nsString& aTag,
nsIDOMNode * aParent,
PRInt32 aPosition,
nsIDOMNode ** aNewNode);
NS_IMETHOD InsertNode(nsIDOMNode * aNode,
nsIDOMNode * aParent,
PRInt32 aPosition);
NS_IMETHOD SplitNode(nsIDOMNode * aExistingRightNode,
PRInt32 aOffset,
nsIDOMNode ** aNewLeftNode);
NS_IMETHOD JoinNodes(nsIDOMNode * aLeftNode,
nsIDOMNode * aRightNode,
nsIDOMNode * aParent);
NS_IMETHOD DeleteNode(nsIDOMNode * aChild);
/* output */
NS_IMETHOD OutputToString(nsString& aOutputString,
const nsString& aFormatType,
PRUint32 aFlags);
NS_IMETHOD OutputToStream(nsIOutputStream* aOutputStream,
const nsString& aFormatType,
const nsString* aCharsetOverride,
PRUint32 aFlags);
/* Listeners */
NS_IMETHOD AddEditActionListener(nsIEditActionListener *aListener);
NS_IMETHOD RemoveEditActionListener(nsIEditActionListener *aListener);
NS_IMETHOD AddDocumentStateListener(nsIDocumentStateListener *aListener);
NS_IMETHOD RemoveDocumentStateListener(nsIDocumentStateListener *aListener);
NS_IMETHOD DumpContentTree();
NS_IMETHOD DebugDumpContent() const;
NS_IMETHOD DebugUnitTests(PRInt32 *outNumTests, PRInt32 *outNumTestsFailed);
/* ------------ nsIEditorIMESupport methods -------------- */
NS_IMETHOD BeginComposition(void);
NS_IMETHOD SetCompositionString(const nsString& aCompositionString, nsIDOMTextRangeList* aTextRangeList);
NS_IMETHOD EndComposition(void);
/* ------------ nsIEditorLogging methods -------------- */
NS_IMETHOD StartLogging(nsIFileSpec *aLogFile);
NS_IMETHOD StopLogging();
public:
NS_IMETHOD InsertTextImpl(const nsString& aStringToInsert);
NS_IMETHOD DeleteSelectionImpl(ESelectionCollapseDirection aAction);
protected:
// why not use the one in nsHTMLDocument?
NS_IMETHOD GetBodyElement(nsIDOMElement **aElement);
//NOTE: Most callers are dealing with Nodes,
// but these objects must supports nsIDOMElement
NS_IMETHOD CopyAttributes(nsIDOMNode *aDestNode, nsIDOMNode *aSourceNode);
/*
NS_IMETHOD SetProperties(nsVoidArray *aPropList);
NS_IMETHOD GetProperties(nsVoidArray *aPropList);
*/
/** create a transaction for setting aAttribute to aValue on aElement
*/
NS_IMETHOD CreateTxnForSetAttribute(nsIDOMElement *aElement,
const nsString& aAttribute,
const nsString& aValue,
ChangeAttributeTxn ** aTxn);
/** create a transaction for removing aAttribute on aElement
*/
NS_IMETHOD CreateTxnForRemoveAttribute(nsIDOMElement *aElement,
const nsString& aAttribute,
ChangeAttributeTxn ** aTxn);
/** create a transaction for creating a new child node of aParent of type aTag.
*/
NS_IMETHOD CreateTxnForCreateElement(const nsString& aTag,
nsIDOMNode *aParent,
PRInt32 aPosition,
CreateElementTxn ** aTxn);
/** create a transaction for inserting aNode as a child of aParent.
*/
NS_IMETHOD CreateTxnForInsertElement(nsIDOMNode * aNode,
nsIDOMNode * aParent,
PRInt32 aOffset,
InsertElementTxn ** aTxn);
/** create a transaction for removing aElement from its parent.
*/
NS_IMETHOD CreateTxnForDeleteElement(nsIDOMNode * aElement,
DeleteElementTxn ** aTxn);
/** Create an aggregate transaction for deleting current selection
* Used by all methods that need to delete current selection,
* then insert something new to replace it
* @param nsString& aTxnName is the name of the aggregated transaction
* @param EditTxn **aAggTxn is the return location of the aggregate TXN,
* with the DeleteSelectionTxn as the first child ONLY
* if there was a selection to delete.
*/
NS_IMETHOD CreateAggregateTxnForDeleteSelection(nsIAtom *aTxnName, EditAggregateTxn **aAggTxn);
NS_IMETHOD CreateTxnForDeleteSelection(ESelectionCollapseDirection aAction,
EditAggregateTxn ** aTxn);
NS_IMETHOD CreateTxnForDeleteInsertionPoint(nsIDOMRange *aRange,
ESelectionCollapseDirection aAction,
EditAggregateTxn *aTxn);
/** create a transaction for inserting aStringToInsert into aTextNode
* if aTextNode is null, the string is inserted at the current selection.
*/
NS_IMETHOD CreateTxnForInsertText(const nsString & aStringToInsert,
nsIDOMCharacterData *aTextNode,
InsertTextTxn ** aTxn);
NS_IMETHOD CreateTxnForIMEText(const nsString & aStringToInsert,
nsIDOMTextRangeList* aTextRangeList,
IMETextTxn ** aTxn);
/** create a transaction for adding a style sheet
*/
NS_IMETHOD CreateTxnForAddStyleSheet(nsICSSStyleSheet* aSheet, AddStyleSheetTxn* *aTxn);
/** create a transaction for removing a style sheet
*/
NS_IMETHOD CreateTxnForRemoveStyleSheet(nsICSSStyleSheet* aSheet, RemoveStyleSheetTxn* *aTxn);
/** insert aStringToInsert as the first text in the document
*/
NS_IMETHOD DoInitialInsert(const nsString & aStringToInsert);
NS_IMETHOD DoInitialInputMethodInsert(const nsString& aStringToInsert,nsIDOMTextRangeList* aTextRangeList);
NS_IMETHOD DeleteText(nsIDOMCharacterData *aElement,
PRUint32 aOffset,
PRUint32 aLength);
NS_IMETHOD CreateTxnForDeleteText(nsIDOMCharacterData *aElement,
PRUint32 aOffset,
PRUint32 aLength,
DeleteTextTxn **aTxn);
NS_IMETHOD CreateTxnForSplitNode(nsIDOMNode *aNode,
PRUint32 aOffset,
SplitElementTxn **aTxn);
NS_IMETHOD CreateTxnForJoinNode(nsIDOMNode *aLeftNode,
nsIDOMNode *aRightNode,
JoinElementTxn **aTxn);
NS_IMETHOD SetInputMethodText(const nsString& aStringToInsert, nsIDOMTextRangeList* aTextRangeList);
// called each time we modify the document. Increments the mod
// count of the doc.
NS_IMETHOD IncDocModCount(PRInt32 inNumMods);
// return the mod count of the doc we are editing. Zero means unchanged.
NS_IMETHOD GetDocModCount(PRInt32 &outModCount);
// called ONLY when we need to override the doc's modification
// state. This should already be handled by nsIDiskDocument.
NS_IMETHOD ResetDocModCount();
// called after a transaction is done successfully
NS_IMETHOD DoAfterDoTransaction(nsITransaction *aTxn);
// called after a transaction is undone successfully
NS_IMETHOD DoAfterUndoTransaction();
// called after a transaction is redone successfully
NS_IMETHOD DoAfterRedoTransaction();
// called after the document has been saved
NS_IMETHOD DoAfterDocumentSave();
typedef enum {
eDocumentCreated,
eDocumentToBeDestroyed,
eDocumentStateChanged
} TDocumentListenerNotification;
// tell the doc state listeners that the doc state has changed
NS_IMETHOD NotifyDocumentListeners(TDocumentListenerNotification aNotificationType);
/** make the given selection span the entire document */
NS_IMETHOD SelectEntireDocument(nsIDOMSelection *aSelection);
protected:
// XXXX: Horrible hack! We are doing this because
// of an error in Gecko which is not rendering the
// document after a change via the DOM - gpk 2/13/99
void HACKForceRedraw(void);
// file handling utils
NS_IMETHOD SaveDocument(PRBool saveAs, PRBool saveCopy);
NS_IMETHOD ScrollIntoView(PRBool aScrollToBegin);
public:
static nsString& GetTextNodeTag();
/**
* SplitNode() creates a new node identical to an existing node, and split the contents between the two nodes
* @param aExistingRightNode the node to split. It will become the new node's next sibling.
* @param aOffset the offset of aExistingRightNode's content|children to do the split at
* @param aNewLeftNode [OUT] the new node resulting from the split, becomes aExistingRightNode's previous sibling.
* @param aParent the parent of aExistingRightNode
*/
static nsresult SplitNodeImpl(nsIDOMNode *aExistingRightNode,
PRInt32 aOffset,
nsIDOMNode *aNewLeftNode,
nsIDOMNode *aParent);
/**
* JoinNodes() takes 2 nodes and merge their content|children.
* @param aNodeToKeep The node that will remain after the join.
* @param aNodeToJoin The node that will be joined with aNodeToKeep.
* There is no requirement that the two nodes be of the same type.
* @param aParent The parent of aExistingRightNode
* @param aNodeToKeepIsFirst if PR_TRUE, the contents|children of aNodeToKeep come before the
* contents|children of aNodeToJoin, otherwise their positions are switched.
*/
static nsresult JoinNodesImpl(nsIDOMNode *aNodeToKeep,
nsIDOMNode *aNodeToJoin,
nsIDOMNode *aParent,
PRBool aNodeToKeepIsFirst);
/**
* Set aOffset to the offset of aChild in aParent.
* Returns an error if aChild is not an immediate child of aParent.
*/
static nsresult GetChildOffset(nsIDOMNode *aChild,
nsIDOMNode *aParent,
PRInt32 &aOffset);
/**
* Set aParent to the parent of aChild.
* Set aOffset to the offset of aChild in aParent.
*/
static nsresult GetNodeLocation(nsIDOMNode *aChild,
nsCOMPtr<nsIDOMNode> *aParent,
PRInt32 *aOffset);
/** set aIsInline to PR_TRUE if aNode is inline as defined by HTML DTD */
static nsresult IsNodeInline(nsIDOMNode *aNode, PRBool &aIsInline);
/** set aIsBlock to PR_TRUE if aNode is inline as defined by HTML DTD */
static nsresult IsNodeBlock(nsIDOMNode *aNode, PRBool &aIsBlock);
/** returns the closest block parent of aNode, not including aNode itself.
* can return null, for example if aNode is in a document fragment.
* @param aNode The node whose parent we seek.
* @param aBlockParent [OUT] The block parent, if any.
* @return a success value unless an unexpected error occurs.
*/
static nsresult GetBlockParent(nsIDOMNode *aNode,
nsIDOMElement **aBlockParent);
/** Determines the bounding nodes for the block section containing aNode.
* The calculation is based on some nodes intrinsically being block elements
* acording to HTML. Style sheets are not considered in this calculation.
* <BR> tags separate block content sections. So the HTML markup:
* <PRE>
* <P>text1<BR>text2<B>text3</B></P>
* </PRE>
* contains two block content sections. The first has the text node "text1"
* for both endpoints. The second has "text2" as the left endpoint and
* "text3" as the right endpoint.
* Notice that offsets aren't required, only leaf nodes. Offsets are implicit.
*
* @param aNode the block content returned includes aNode
* @param aLeftNode [OUT] the left endpoint of the block content containing aNode
* @param aRightNode [OUT] the right endpoint of the block content containing aNode
*
*/
static nsresult GetBlockSection(nsIDOMNode *aNode,
nsIDOMNode **aLeftNode,
nsIDOMNode **aRightNode);
/** Compute the set of block sections in a given range.
* A block section is the set of (leftNode, rightNode) pairs given
* by GetBlockSection. The set is computed by computing the
* block section for every leaf node in the range and throwing
* out duplicates.
*
* @param aRange The range to compute block sections for.
* @param aSections Allocated storage for the resulting set, stored as nsIDOMRanges.
*/
static nsresult GetBlockSectionsForRange(nsIDOMRange *aRange,
nsISupportsArray *aSections);
/** returns PR_TRUE in out-param aResult if all nodes between (aStartNode, aStartOffset)
* and (aEndNode, aEndOffset) are inline as defined by HTML DTD.
*/
static nsresult IntermediateNodesAreInline(nsIDOMRange *aRange,
nsIDOMNode *aStartNode,
PRInt32 aStartOffset,
nsIDOMNode *aEndNode,
PRInt32 aEndOffset,
PRBool &aResult);
/** returns the number of things inside aNode in the out-param aCount.
* @param aNode is the node to get the length of.
* If aNode is text, returns number of characters.
* If not, returns number of children nodes.
* @param aCount [OUT] the result of the above calculation.
*/
static nsresult GetLengthOfDOMNode(nsIDOMNode *aNode, PRUint32 &aCount);
/** get the node immediately prior to aCurrentNode
* @param aCurrentNode the node from which we start the search
* @param aEditableNode if PR_TRUE, only return an editable node
* @param aResultNode [OUT] the node that occurs before aCurrentNode in the tree,
* skipping non-editable nodes if aEditableNode is PR_TRUE.
* If there is no prior node, aResultNode will be nsnull.
*/
nsresult GetPriorNode(nsIDOMNode *aCurrentNode,
PRBool aEditableNode,
nsIDOMNode **aResultNode);
/** get the node immediately after to aCurrentNode
* @param aCurrentNode the node from which we start the search
* @param aEditableNode if PR_TRUE, only return an editable node
* @param aResultNode [OUT] the node that occurs after aCurrentNode in the tree,
* skipping non-editable nodes if aEditableNode is PR_TRUE.
* If there is no prior node, aResultNode will be nsnull.
*/
nsresult GetNextNode(nsIDOMNode *aCurrentNode,
PRBool aEditableNode,
nsIDOMNode **aResultNode);
/** Get the rightmost child of aCurrentNode, and return it in aResultNode
* aResultNode is set to nsnull if aCurrentNode has no children.
*/
static nsresult GetRightmostChild(nsIDOMNode *aCurrentNode, nsIDOMNode **aResultNode);
/** Get the leftmost child of aCurrentNode, and return it in aResultNode
* aResultNode is set to nsnull if aCurrentNode has no children.
*/
static nsresult GetLeftmostChild(nsIDOMNode *aCurrentNode, nsIDOMNode **aResultNode);
/** GetFirstTextNode ADDREFFS and will get the next available text node from the passed
* in node parameter it can also return NS_ERROR_FAILURE if no text nodes are available
* now it simply returns the first node in the dom
* @param nsIDOMNode *aNode is the node to start looking from
* @param nsIDOMNode **aRetNode is the return location of the text dom node
*
* NOTE: this method will probably be removed.
*/
static nsresult GetFirstTextNode(nsIDOMNode *aNode, nsIDOMNode **aRetNode);
/** GetFirstNodeOfType ADDREFFS and will get the next available node from the passed
* in aStartNode parameter of type aTag.
* It can also return NS_ERROR_FAILURE if no such nodes are available
* @param aStartNode is the node to start looking from
* @param aTag is the type of node we are searching for
* @param aResult is the node we found, or nsnull if there is none
*/
static nsresult GetFirstNodeOfType(nsIDOMNode *aStartNode,
const nsString &aTag,
nsIDOMNode **aResult);
/** returns PR_TRUE if aNode is of the type implied by aTag */
static PRBool NodeIsType(nsIDOMNode *aNode, nsIAtom *aTag);
/** returns PR_TRUE if aParent can contain a child of type aTag */
PRBool CanContainTag(nsIDOMNode* aParent, const nsString &aTag);
/** returns PR_TRUE if aNode is an editable node */
PRBool IsEditable(nsIDOMNode *aNode);
/** counts number of editable child nodes */
nsresult CountEditableChildren(nsIDOMNode *aNode, PRUint32 &outCount);
/** Find the deep first and last children */
nsCOMPtr<nsIDOMNode> GetDeepFirstChild(nsCOMPtr<nsIDOMNode> aRoot);
nsCOMPtr<nsIDOMNode> GetDeepLastChild(nsCOMPtr<nsIDOMNode> aRoot);
/** from html rules code - migration in progress */
static nsresult GetTagString(nsIDOMNode *aNode, nsString& outString);
static nsCOMPtr<nsIAtom> GetTag(nsIDOMNode *aNode);
static PRBool NodesSameType(nsIDOMNode *aNode1, nsIDOMNode *aNode2);
static PRBool IsBlockNode(nsIDOMNode *aNode);
static PRBool IsInlineNode(nsIDOMNode *aNode);
static nsCOMPtr<nsIDOMNode> GetBlockNodeParent(nsIDOMNode *aNode);
static PRBool HasSameBlockNodeParent(nsIDOMNode *aNode1, nsIDOMNode *aNode2);
static PRBool IsTextOrElementNode(nsIDOMNode *aNode);
static PRBool IsTextNode(nsIDOMNode *aNode);
static PRInt32 GetIndexOf(nsIDOMNode *aParent, nsIDOMNode *aChild);
static nsCOMPtr<nsIDOMNode> GetChildAt(nsIDOMNode *aParent, PRInt32 aOffset);
static nsCOMPtr<nsIDOMNode> NextNodeInBlock(nsIDOMNode *aNode, IterDirection aDir);
static nsresult GetStartNodeAndOffset(nsIDOMSelection *aSelection, nsCOMPtr<nsIDOMNode> *outStartNode, PRInt32 *outStartOffset);
static nsresult GetEndNodeAndOffset(nsIDOMSelection *aSelection, nsCOMPtr<nsIDOMNode> *outEndNode, PRInt32 *outEndOffset);
nsresult IsPreformatted(nsIDOMNode *aNode, PRBool *aResult);
nsresult IsNextCharWhitespace(nsIDOMNode *aParentNode, PRInt32 aOffset, PRBool *aResult);
nsresult IsPrevCharWhitespace(nsIDOMNode *aParentNode, PRInt32 aOffset, PRBool *aResult);
nsresult SplitNodeDeep(nsIDOMNode *aNode, nsIDOMNode *aSplitPointParent, PRInt32 aSplitPointOffset);
nsresult JoinNodeDeep(nsIDOMNode *aLeftNode, nsIDOMNode *aRightNode, nsIDOMSelection *aSelection);
nsresult GetString(const nsString& name, nsString& value);
nsresult BeginUpdateViewBatch(void);
nsresult EndUpdateViewBatch(void);
protected:
PRUint32 mFlags; // behavior flags. See nsIHighLevelHTMLEditor.h for the flags we use.
nsIPresShell *mPresShell;
nsIViewManager *mViewManager;
PRUint32 mUpdateCount;
nsCOMPtr<nsITransactionManager> mTxnMgr;
nsCOMPtr<nsIEditProperty> mEditProperty;
nsCOMPtr<nsICSSStyleSheet> mLastStyleSheet; // is owning this dangerous?
//
// data necessary to build IME transactions
//
nsCOMPtr<nsIDOMCharacterData> mIMETextNode;
PRUint32 mIMETextOffset;
PRUint32 mIMEBufferLength;
nsVoidArray* mActionListeners;
nsCOMPtr<nsISupportsArray> mDocStateListeners;
nsCOMPtr<nsIStringBundle> mStringBundle;
PRInt8 mDocDirtyState; // -1 = not initialized
nsIDOMDocument * mDoc;
nsCOMPtr<nsIDTD> mDTD;
// Services are not nsCOMPtr friendly
nsIPref* mPrefs;
#ifdef ENABLE_JS_EDITOR_LOG
nsJSEditorLog *mJSEditorLog;
nsJSTxnLog *mJSTxnLog;
#endif // ENABLE_JS_EDITOR_LOG
static PRInt32 gInstanceCount;
friend PRBool NSCanUnload(nsISupports* serviceMgr);
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,268 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef editorInterfaces_h__
#define editorInterfaces_h__
#include "nsCOMPtr.h"
#include "nsIDOMEvent.h"
#include "nsIDOMKeyListener.h"
#include "nsIDOMMouseListener.h"
#include "nsIDOMTextListener.h"
#include "nsIDOMDragListener.h"
#include "nsIDOMCompositionListener.h"
#include "nsIDOMFocusListener.h"
#include "nsIEditor.h"
#include "nsIHighLevelHTMLEditor.h"
/** The nsTextEditorKeyListener public nsIDOMKeyListener
* This class will delegate events to its editor according to the translation
* it is responsible for. i.e. 'c' becomes a keydown, but 'ESC' becomes nothing.
*/
class nsTextEditorKeyListener : public nsIDOMKeyListener {
public:
/** the default constructor
*/
nsTextEditorKeyListener();
/** the default destructor. virtual due to the possibility of derivation.
*/
virtual ~nsTextEditorKeyListener();
/** SetEditor gives an address to the editor that will be accessed
* @param aEditor the editor this listener calls for editing operations
*/
void SetEditor(nsIEditor *aEditor){mEditor = aEditor;}
/*interfaces for addref and release and queryinterface*/
NS_DECL_ISUPPORTS
/*BEGIN interfaces in to the keylister base interface. must be supplied to handle pure virtual interfaces
see the nsIDOMKeyListener interface implementation for details
*/
virtual nsresult HandleEvent(nsIDOMEvent* aEvent);
virtual nsresult KeyDown(nsIDOMEvent* aKeyEvent);
virtual nsresult KeyUp(nsIDOMEvent* aKeyEvent);
virtual nsresult KeyPress(nsIDOMEvent* aKeyEvent);
/*END interfaces from nsIDOMKeyListener*/
protected:
virtual nsresult ProcessShortCutKeys(nsIDOMEvent* aKeyEvent, PRBool& aProcessed);
protected:
nsIEditor* mEditor; // weak reference
};
/** editor Implementation of the MouseListener interface
*/
class nsTextEditorTextListener : public nsIDOMTextListener
{
public:
/** default constructor
*/
nsTextEditorTextListener();
/** default destructor
*/
virtual ~nsTextEditorTextListener();
/** SetEditor gives an address to the editor that will be accessed
* @param aEditor the editor this listener calls for editing operations
*/
void SetEditor(nsIEditor *aEditor){mEditor = aEditor;}
/*interfaces for addref and release and queryinterface*/
NS_DECL_ISUPPORTS
/*BEGIN implementations of textevent handler interface*/
virtual nsresult HandleEvent(nsIDOMEvent* aEvent);
public:
virtual nsresult HandleText(nsIDOMEvent* aTextEvent);
/*END implementations of textevent handler interface*/
protected:
nsIEditor* mEditor; // weak reference
PRBool mCommitText;
PRBool mInTransaction;
};
class nsIEditorIMESupport;
class nsTextEditorCompositionListener : public nsIDOMCompositionListener
{
public:
/** default constructor
*/
nsTextEditorCompositionListener();
/** default destructor
*/
virtual ~nsTextEditorCompositionListener();
/** SetEditor gives an address to the editor that will be accessed
* @param aEditor the editor this listener calls for editing operations
*/
void SetEditor(nsIEditor *aEditor);
/*interfaces for addref and release and queryinterface*/
NS_DECL_ISUPPORTS
/*BEGIN implementations of textevent handler interface*/
virtual nsresult HandleEvent(nsIDOMEvent* aEvent);
public:
virtual nsresult HandleStartComposition(nsIDOMEvent* aCompositionEvent);
virtual nsresult HandleEndComposition(nsIDOMEvent* aCompositionEvent);
/*END implementations of textevent handler interface*/
protected:
nsIEditorIMESupport* mEditor; // weak reference
};
/** editor Implementation of the TextListener interface
*/
class nsTextEditorMouseListener : public nsIDOMMouseListener
{
public:
/** default constructor
*/
nsTextEditorMouseListener();
/** default destructor
*/
virtual ~nsTextEditorMouseListener();
/** SetEditor gives an address to the editor that will be accessed
* @param aEditor the editor this listener calls for editing operations
*/
void SetEditor(nsIEditor *aEditor){mEditor = aEditor;}
/*interfaces for addref and release and queryinterface*/
NS_DECL_ISUPPORTS
/*BEGIN implementations of mouseevent handler interface*/
virtual nsresult HandleEvent(nsIDOMEvent* aEvent);
public:
virtual nsresult MouseDown(nsIDOMEvent* aMouseEvent);
virtual nsresult MouseUp(nsIDOMEvent* aMouseEvent);
virtual nsresult MouseClick(nsIDOMEvent* aMouseEvent);
virtual nsresult MouseDblClick(nsIDOMEvent* aMouseEvent);
virtual nsresult MouseOver(nsIDOMEvent* aMouseEvent);
virtual nsresult MouseOut(nsIDOMEvent* aMouseEvent);
/*END implementations of mouseevent handler interface*/
protected:
nsIEditor* mEditor; // weak reference
};
/** editor Implementation of the MouseListener interface
*/
class nsTextEditorDragListener : public nsIDOMDragListener
{
public:
/** default constructor
*/
nsTextEditorDragListener();
/** default destructor
*/
virtual ~nsTextEditorDragListener();
/** SetEditor gives an address to the editor that will be accessed
* @param aEditor the editor this listener calls for editing operations
*/
void SetEditor(nsIEditor *aEditor){mEditor = aEditor;}
/*interfaces for addref and release and queryinterface*/
NS_DECL_ISUPPORTS
/*BEGIN implementations of dragevent handler interface*/
virtual nsresult HandleEvent(nsIDOMEvent* aEvent);
public:
virtual nsresult DragEnter(nsIDOMEvent* aDragEvent);
virtual nsresult DragOver(nsIDOMEvent* aDragEvent);
virtual nsresult DragExit(nsIDOMEvent* aDragEvent);
virtual nsresult DragDrop(nsIDOMEvent* aDragEvent);
/*END implementations of dragevent handler interface*/
protected:
nsIEditor* mEditor;
};
/** editor Implementation of the FocusListener interface
*/
class nsTextEditorFocusListener : public nsIDOMFocusListener
{
public:
/** default constructor
*/
nsTextEditorFocusListener();
/** default destructor
*/
virtual ~nsTextEditorFocusListener();
/** SetEditor gives an address to the editor that will be accessed
* @param aEditor the editor this listener calls for editing operations
*/
void SetEditor(nsIEditor *aEditor){mEditor = aEditor;}
/*interfaces for addref and release and queryinterface*/
NS_DECL_ISUPPORTS
/*BEGIN implementations of focus event handler interface*/
virtual nsresult HandleEvent(nsIDOMEvent* aEvent);
public:
virtual nsresult Focus(nsIDOMEvent* aEvent);
virtual nsresult Blur(nsIDOMEvent* aEvent);
/*END implementations of focus event handler interface*/
protected:
nsIEditor* mEditor; // weak reference
};
/** factory for the editor key listener
*/
extern nsresult NS_NewEditorKeyListener(nsIDOMEventListener ** aInstancePtrResult, nsIEditor *aEditor);
/** factory for the editor mouse listener
*/
extern nsresult NS_NewEditorMouseListener(nsIDOMEventListener ** aInstancePtrResult, nsIEditor *aEditor);
/** factory for the editor text listener
*/
extern nsresult NS_NewEditorTextListener(nsIDOMEventListener** aInstancePtrResult, nsIEditor *aEditor);
/** factory for the editor drag listener
*/
extern nsresult NS_NewEditorDragListener(nsIDOMEventListener ** aInstancePtrResult, nsIEditor *aEditor);
/** factory for the editor composition listener
*/
extern nsresult NS_NewEditorCompositionListener(nsIDOMEventListener** aInstancePtrResult, nsIEditor *aEditor);
/** factory for the editor composition listener
*/
extern nsresult NS_NewEditorFocusListener(nsIDOMEventListener** aInstancePtrResult, nsIEditor *aEditor);
#endif //editorInterfaces_h__

View File

@@ -0,0 +1,150 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsCOMPtr.h"
#include "nsEditorFactory.h"
#include "nsIEditor.h"
#include "nsIHighLevelHTMLEditor.h"
#include "nsEditorShell.h"
#include "nsEditorShellFactory.h"
#include "nsHTMLEditor.h"
#include "nsEditor.h"
#include "nsEditorCID.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
static NS_DEFINE_IID(kHTMLEditorCID, NS_HTMLEDITOR_CID);
nsresult
GetEditorFactory(nsIFactory **aFactory, const nsCID & aClass)
{
// XXX Note static which never gets released, even on library unload.
// XXX Was an nsCOMPtr but that caused a crash on exit,
// XXX http://bugzilla.mozilla.org/show_bug.cgi?id=7938
PR_EnterMonitor(GetEditorMonitor());
nsEditorFactory *factory = new nsEditorFactory(aClass);
if (!factory)
return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsIFactory> pNSIFactory = do_QueryInterface(factory);
if (!pNSIFactory)
return NS_ERROR_NO_INTERFACE;
nsresult result = pNSIFactory->QueryInterface(nsIFactory::GetIID(),
(void **)aFactory);
PR_ExitMonitor(GetEditorMonitor());
return result;
}
nsEditorFactory::nsEditorFactory(const nsCID &aClass)
: mCID(aClass)
{
NS_INIT_REFCNT();
}
nsEditorFactory::~nsEditorFactory()
{
//nsComponentManager::UnregisterFactory(mCID, (nsIFactory *)this); //we are out of ref counts anyway
}
////////////////////////////////////////////////////////////////////////////
// from nsISupports
NS_METHOD
nsEditorFactory::QueryInterface(const nsIID& aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
NS_NOTREACHED("!nsEditor");
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(nsIFactory::GetIID()) ||
aIID.Equals(nsCOMTypeInfo<nsISupports>::GetIID())) {
*aInstancePtr = (void*) this;
AddRef();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMPL_ADDREF(nsEditorFactory)
NS_IMPL_RELEASE(nsEditorFactory)
////////////////////////////////////////////////////////////////////////////
// from nsIFactory:
NS_METHOD
nsEditorFactory::CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
*aResult = nsnull;
nsISupports *obj = nsnull;
if (!aResult)
return NS_ERROR_NULL_POINTER;
if (aOuter && !aIID.Equals(nsCOMTypeInfo<nsISupports>::GetIID()))
return NS_NOINTERFACE; // XXX right error?
/* nsEditor is pure virtual
if (mCID.Equals(kEditorCID))
obj = (nsISupports *)(nsIEditor*)new nsEditor();
*/
if (mCID.Equals(kHTMLEditorCID))
{
//Need to cast to interface first to avoid "ambiguous conversion..." error
// because of multiple nsISupports in the class hierarchy
obj = (nsISupports *)(nsIHighLevelHTMLEditor*)new nsHTMLEditor();
}
if (obj && NS_FAILED(obj->QueryInterface(aIID, (void**)aResult)) )
{
delete obj;
return NS_NOINTERFACE;
}
return NS_OK;
}
NS_METHOD
nsEditorFactory::LockFactory(PRBool aLock)
{
return NS_OK;
}
//if more than one person asks for the monitor at the same time for the FIRST time, we are screwed
PRMonitor *GetEditorMonitor()
{
static PRMonitor *ns_editlock = nsnull;
if (nsnull == ns_editlock)
{
ns_editlock = (PRMonitor *)1; //how long will the next line take? lets cut down on the chance of reentrancy
ns_editlock = PR_NewMonitor();
}
else if ((PRMonitor *)1 == ns_editlock)
return GetEditorMonitor();
return ns_editlock;
}

View File

@@ -0,0 +1,67 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIEditFactory_h___
#define nsIEditFactory_h___
#include "nsISupports.h"
#include "nsIFactory.h"
/*
EditFactory that can make an editor
*/
/**
* This supplies the neccessary entrance to the edit module. it will return any
* instantiations that we need.
*/
nsresult GetEditorFactory(nsIFactory **aFactory, const nsCID & aClass);
class nsEditorFactory : public nsIFactory
{
public:
////////////////////////////////////////////////////////////////////////////
// from nsISupports and AggregatedQueryInterface:
NS_DECL_ISUPPORTS
////////////////////////////////////////////////////////////////////////////
// from nsIFactory:
NS_IMETHOD
CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult);
NS_IMETHOD
LockFactory(PRBool aLock);
////////////////////////////////////////////////////////////////////////////
// from nsEditFactory:
virtual ~nsEditorFactory(void);
private:
nsEditorFactory(const nsCID &aClass); //will fill the aFactory with the result from queryinterface
/** getEditFactory
* creates an edit factory other CSID supported friend functions here.
*/
friend nsresult GetEditorFactory(nsIFactory **, const nsCID & );
const nsCID &mCID;
};
#endif //nsIEditFactory_h___

View File

@@ -0,0 +1,154 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsCOMPtr.h"
#include "nsIServiceManager.h"
#include "nsIComponentManager.h"
#include "nsEditorCID.h"
#include "nsEditorShell.h" // for the CID
#include "nsEditorShellFactory.h"
#include "nsEditor.h" // for gInstanceCount
#include "nsEditorFactory.h"
static NS_DEFINE_CID(kComponentManagerCID, NS_COMPONENTMANAGER_CID);
static NS_DEFINE_IID(kHTMLEditorCID, NS_HTMLEDITOR_CID);
static NS_DEFINE_IID(kEditorShellCID, NS_EDITORSHELL_CID);
/*
we must be good providers of factories etc. this is where to put ALL editor exports
*/
//BEGIN EXPORTS
extern "C" NS_EXPORT nsresult NSGetFactory(nsISupports * aServMgr,
const nsCID & aClass,
const char * aClassName,
const char * aProgID,
nsIFactory ** aFactory)
{
if (nsnull == aFactory) {
return NS_ERROR_NULL_POINTER;
}
*aFactory = nsnull;
nsresult rv;
nsCOMPtr<nsIServiceManager> servMgr(do_QueryInterface(aServMgr, &rv));
if (NS_FAILED(rv)) return rv;
nsIComponentManager* componentManager = nsnull;
rv = servMgr->GetService(kComponentManagerCID, nsIComponentManager::GetIID(),
(nsISupports**)&componentManager);
if (NS_FAILED(rv)) return rv;
rv = NS_NOINTERFACE;
if (aClass.Equals(kHTMLEditorCID)) {
rv = GetEditorFactory(aFactory, aClass);
if (NS_FAILED(rv)) goto done;
}
else if (aClass.Equals(kEditorShellCID)) {
rv = GetEditorShellFactory(aFactory, aClass, aClassName, aProgID);
if (NS_FAILED(rv)) goto done;
}
done:
(void)servMgr->ReleaseService(kComponentManagerCID, componentManager);
return rv;
}
extern "C" NS_EXPORT PRBool
NSCanUnload(nsISupports* aServMgr)
{
return nsEditor::gInstanceCount;
}
extern "C" NS_EXPORT nsresult
NSRegisterSelf(nsISupports* aServMgr, const char *path)
{
nsresult rv;
nsCOMPtr<nsIServiceManager> servMgr(do_QueryInterface(aServMgr, &rv));
if (NS_FAILED(rv)) return rv;
nsIComponentManager* compMgr;
rv = servMgr->GetService(kComponentManagerCID,
nsIComponentManager::GetIID(),
(nsISupports**)&compMgr);
if (NS_FAILED(rv)) return rv;
rv = compMgr->RegisterComponent(kHTMLEditorCID, NULL, NULL, path,
PR_TRUE, PR_TRUE);
if (NS_FAILED(rv)) goto done;
rv = compMgr->RegisterComponent(kEditorShellCID,
"Editor Shell Component",
"component://netscape/editor/editorshell",
path, PR_TRUE, PR_TRUE);
if (NS_FAILED(rv)) goto done;
rv = compMgr->RegisterComponent(kEditorShellCID,
"Editor Shell Spell Checker",
"component://netscape/editor/editorspellcheck",
path, PR_TRUE, PR_TRUE);
done:
(void)servMgr->ReleaseService(kComponentManagerCID, compMgr);
return rv;
}
extern "C" NS_EXPORT nsresult
NSUnregisterSelf(nsISupports* aServMgr, const char *path)
{
nsresult rv;
nsCOMPtr<nsIServiceManager> servMgr(do_QueryInterface(aServMgr, &rv));
if (NS_FAILED(rv)) return rv;
nsIComponentManager* compMgr;
rv = servMgr->GetService(kComponentManagerCID,
nsIComponentManager::GetIID(),
(nsISupports**)&compMgr);
if (NS_FAILED(rv)) return rv;
/*
rv = compMgr->UnregisterComponent(kEditorCID, path);
if (NS_FAILED(rv)) goto done;
rv = compMgr->UnregisterComponent(kTextEditorCID, path);
if (NS_FAILED(rv)) goto done;
*/
rv = compMgr->UnregisterComponent(kHTMLEditorCID, path);
if (NS_FAILED(rv)) goto done;
rv = compMgr->UnregisterComponent(kEditorShellCID, path);
done:
(void)servMgr->ReleaseService(kComponentManagerCID, compMgr);
return rv;
}
//END EXPORTS

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,338 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsEditorShell_h___
#define nsEditorShell_h___
//#include "nsAppCores.h"
#include "nscore.h"
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsISupports.h"
#include "nsIEditorShell.h"
#include "nsIDocumentLoaderObserver.h"
#include "nsIDOMSelectionListener.h"
#ifdef NECKO
#include "nsIPrompt.h"
#else
#include "nsINetSupport.h"
#endif
#include "nsIStreamObserver.h"
#include "nsIDOMDocument.h"
#include "nsVoidArray.h"
#include "nsTextServicesCID.h"
#include "nsIEditorSpellCheck.h"
#include "nsISpellChecker.h"
#include "nsInterfaceState.h"
#include "nsIHighLevelHTMLEditor.h"
class nsIBrowserWindow;
class nsIWebShell;
class nsIScriptContext;
class nsIDOMWindow;
class nsIDOMElement;
class nsIDOMNode;
class nsIURI;
class nsIWebShellWindow;
class nsIPresShell;
class nsIOutputStream;
class nsISupportsArray;
#define NS_EDITORSHELL_CID \
{ /* {} */ \
0x9afff72b, 0xca9a, 0x11d2, \
{ 0x96, 0xc9, 0x0, 0x60, 0xb0, 0xfb, 0x99, 0x56 } \
}
////////////////////////////////////////////////////////////////////////////////
// nsEditorShell:
////////////////////////////////////////////////////////////////////////////////
class nsEditorShell : public nsIEditorShell,
public nsIEditorSpellCheck,
public nsIDocumentLoaderObserver
{
public:
nsEditorShell();
virtual ~nsEditorShell();
NS_DECL_ISUPPORTS
// NS_IMETHOD GetScriptObject(nsIScriptContext *aContext, void** aScriptObject);
NS_IMETHOD Init();
// NS_IMETHOD GetId(nsString& aId); // { return nsBaseAppCore::GetId(aId); }
// NS_IMETHOD SetDocumentCharset(const nsString& aCharset); // { return nsBaseAppCore::SetDocumentCharset(aCharset); }
/* nsIEditorShell interface */
NS_IMETHOD GetEditorDocument(nsIDOMDocument * *aEditorDocument);
NS_IMETHOD GetEditorSelection(nsIDOMSelection * *aEditorSelection);
NS_IMETHOD GetDocumentModified(PRBool *aDocumentModified);
NS_IMETHOD GetWrapColumn(PRInt32 *aWrapColumn);
NS_IMETHOD SetWrapColumn(PRInt32 aWrapColumn);
NS_IMETHOD SetEditorType(const PRUnichar *editorType);
NS_IMETHOD SetToolbarWindow(nsIDOMWindow *win);
NS_IMETHOD SetContentWindow(nsIDOMWindow *win);
NS_IMETHOD SetWebShellWindow(nsIDOMWindow *win);
NS_IMETHOD LoadUrl(const PRUnichar *url);
NS_IMETHOD RegisterDocumentStateListener(nsIDocumentStateListener *docListener);
NS_IMETHOD UnregisterDocumentStateListener(nsIDocumentStateListener *docListener);
/* void NewWindow (); */
NS_IMETHOD NewWindow();
NS_IMETHOD Open();
NS_IMETHOD Save();
NS_IMETHOD SaveAs();
NS_IMETHOD CloseWindow();
NS_IMETHOD Print();
NS_IMETHOD Exit();
NS_IMETHOD Undo();
NS_IMETHOD Redo();
NS_IMETHOD Cut();
NS_IMETHOD Copy();
NS_IMETHOD Paste();
NS_IMETHOD PasteAsQuotation();
NS_IMETHOD PasteAsCitedQuotation(const PRUnichar *cite);
NS_IMETHOD InsertAsQuotation(const PRUnichar *quotedText);
NS_IMETHOD InsertAsCitedQuotation(const PRUnichar *quotedText, const PRUnichar *cite);
NS_IMETHOD SelectAll();
NS_IMETHOD DeleteSelection(PRInt32 direction);
/* void Find (); */
NS_IMETHOD Find();
NS_IMETHOD FindNext();
/* void InsertText (in wstring textToInsert); */
NS_IMETHOD InsertText(const PRUnichar *textToInsert);
NS_IMETHOD InsertSource(const PRUnichar *sourceToInsert);
NS_IMETHOD InsertBreak();
NS_IMETHOD InsertList(const PRUnichar *listType);
/* void Indent (in string indent); */
NS_IMETHOD Indent(const PRUnichar *indent);
NS_IMETHOD Align(const PRUnichar *align);
/* nsIDOMElement GetSelectedElement (in wstring tagName); */
NS_IMETHOD GetSelectedElement(const PRUnichar *tagName, nsIDOMElement **_retval);
NS_IMETHOD GetElementOrParentByTagName(const PRUnichar *tagName, nsIDOMNode *aNode, nsIDOMElement **_retval);
NS_IMETHOD CreateElementWithDefaults(const PRUnichar *tagName, nsIDOMElement **_retval);
NS_IMETHOD InsertElement(nsIDOMElement *element, PRBool deleteSelection);
NS_IMETHOD SaveHLineSettings(nsIDOMElement* aElement);
NS_IMETHOD InsertLinkAroundSelection(nsIDOMElement *anchorElement);
NS_IMETHOD SelectElement(nsIDOMElement *element);
NS_IMETHOD SetSelectionAfterElement(nsIDOMElement *element);
/* Table insert and delete methods. Done relative to selected cell or
cell containing the selection anchor */
NS_IMETHOD InsertTableCell(PRInt32 aNumber, PRBool bAfter);
NS_IMETHOD InsertTableRow(PRInt32 aNumber, PRBool bAfter);
NS_IMETHOD InsertTableColumn(PRInt32 aNumber, PRBool bAfter);
NS_IMETHOD DeleteTable();
NS_IMETHOD DeleteTableCell(PRInt32 aNumber);
NS_IMETHOD DeleteTableRow(PRInt32 aNumber);
NS_IMETHOD DeleteTableColumn(PRInt32 aNumber);
NS_IMETHOD JoinTableCells();
/** Make table "rectangular" -- fill in all missing cellmap locations
* If aTable is null, it uses table enclosing the selection anchor
*/
NS_IMETHOD NormalizeTable(nsIDOMElement *aTable);
/* Get the row and col indexes in layout's cellmap */
NS_IMETHOD GetRowIndex(nsIDOMElement *aCell, PRInt32 *_retval);
NS_IMETHOD GetColumnIndex(nsIDOMElement *aCell, PRInt32 *_retval);
/** Get the number of rows in a table from the layout's cellmap */
NS_IMETHOD GetTableRowCount(nsIDOMElement *aTable, PRInt32 *_retval);
/** Get the number of columns in a table from the layout's cellmap */
NS_IMETHOD GetTableColumnCount(nsIDOMElement *aTable, PRInt32 *_retval);
/* Get a cell and associated data from the layout frame based on cell map coordinates (0 index) */
NS_IMETHOD GetCellAt(nsIDOMElement* aTable, PRInt32 aRowIndex, PRInt32 aColIndex, nsIDOMElement **_retval);
/* Note that the return param in the IDL must be the LAST out param here (_retval) */
NS_IMETHOD GetCellDataAt(nsIDOMElement* aTable, PRInt32 aRowIndex, PRInt32 aColIndex,
PRInt32 *aStartRowIndex, PRInt32 *aStartColIndex,
PRInt32 *aRowSpan, PRInt32 *aColSpan, PRBool *aIsSelected, nsIDOMElement **_retval);
/* Get list of embedded objects, e.g. for mail compose */
NS_IMETHOD GetEmbeddedObjects(nsISupportsArray **aObjectArray);
/* void SetParagraphFormat (in string value); */
NS_IMETHOD SetParagraphFormat(PRUnichar *value);
NS_IMETHOD GetParagraphFormat(PRUnichar * *aParagraphFormat);
/* void SetTextProperty (in string prop, in string attr, in string value); */
NS_IMETHOD SetTextProperty(const PRUnichar *prop, const PRUnichar *attr, const PRUnichar *value);
NS_IMETHOD GetTextProperty(const PRUnichar *prop, const PRUnichar *attr, const PRUnichar *value, PRBool *firstHas, PRBool *anyHas, PRBool *allHas);
NS_IMETHOD RemoveTextProperty(const PRUnichar *prop, const PRUnichar *attr);
/* void SetBodyAttribute (in string attr, in string value); */
NS_IMETHOD SetBodyAttribute(const PRUnichar *attr, const PRUnichar *value);
NS_IMETHOD SetBackgroundColor(const PRUnichar *color);
NS_IMETHOD ApplyStyleSheet(const PRUnichar *url);
/* Get the contents, for output or other uses */
NS_IMETHOD GetContentsAs(const PRUnichar *format, PRUint32 flags, PRUnichar **contentsAs);
/* Debugging: dump content tree to stdout */
NS_IMETHOD DumpContentTree();
/* string GetLocalFileURL (in nsIDOMWindow parent, in string filterType); */
NS_IMETHOD GetLocalFileURL(nsIDOMWindow *parent, const PRUnichar *filterType, PRUnichar **_retval);
/* void BeginBatchChanges (); */
NS_IMETHOD BeginBatchChanges();
NS_IMETHOD EndBatchChanges();
/* void RunUnitTests (); */
NS_IMETHOD RunUnitTests();
/* void BeginLogging (); */
NS_IMETHOD StartLogging(nsIFileSpec *logFile);
NS_IMETHOD StopLogging();
/* Spell check interface */
NS_IMETHOD StartSpellChecking(PRUnichar **_retval);
NS_IMETHOD GetNextMisspelledWord(PRUnichar **_retval);
NS_IMETHOD GetSuggestedWord(PRUnichar **_retval);
NS_IMETHOD CheckCurrentWord(const PRUnichar *suggestedWord, PRBool *_retval);
NS_IMETHOD ReplaceWord(const PRUnichar *misspelledWord, const PRUnichar *replaceWord, PRBool allOccurrences);
NS_IMETHOD IgnoreWordAllOccurrences(const PRUnichar *word);
NS_IMETHOD GetPersonalDictionary();
NS_IMETHOD GetPersonalDictionaryWord(PRUnichar **_retval);
NS_IMETHOD AddWordToDictionary(const PRUnichar *word);
NS_IMETHOD RemoveWordFromDictionary(const PRUnichar *word);
NS_IMETHOD CloseSpellChecking();
// nsIDocumentLoaderObserver
NS_IMETHOD OnStartDocumentLoad(nsIDocumentLoader* loader, nsIURI* aURL, const char* aCommand);
#ifndef NECKO
NS_IMETHOD OnEndDocumentLoad(nsIDocumentLoader* loader, nsIURI *aUrl, PRInt32 aStatus,
nsIDocumentLoaderObserver * aObserver);
#else
NS_IMETHOD OnEndDocumentLoad(nsIDocumentLoader* loader, nsIChannel* channel, PRInt32 aStatus,
nsIDocumentLoaderObserver * aObserver);
#endif // NECKO
#ifndef NECKO
NS_IMETHOD OnStartURLLoad(nsIDocumentLoader* loader, nsIURI* aURL, const char* aContentType,
nsIContentViewer* aViewer);
#else
NS_IMETHOD OnStartURLLoad(nsIDocumentLoader* loader, nsIChannel* channel,
nsIContentViewer* aViewer);
#endif // NECKO
#ifndef NECKO
NS_IMETHOD OnProgressURLLoad(nsIDocumentLoader* loader, nsIURI* aURL, PRUint32 aProgress,
PRUint32 aProgressMax);
#else
NS_IMETHOD OnProgressURLLoad(nsIDocumentLoader* loader, nsIChannel* channel, PRUint32 aProgress,
PRUint32 aProgressMax);
#endif // NECKO
#ifndef NECKO
NS_IMETHOD OnStatusURLLoad(nsIDocumentLoader* loader, nsIURI* aURL, nsString& aMsg);
#else
NS_IMETHOD OnStatusURLLoad(nsIDocumentLoader* loader, nsIChannel* channel, nsString& aMsg);
#endif // NECKO
#ifndef NECKO
NS_IMETHOD OnEndURLLoad(nsIDocumentLoader* loader, nsIURI* aURL, PRInt32 aStatus);
#else
NS_IMETHOD OnEndURLLoad(nsIDocumentLoader* loader, nsIChannel* channel, PRInt32 aStatus);
#endif // NECKO
#ifndef NECKO
NS_IMETHOD HandleUnknownContentType(nsIDocumentLoader* loader,
nsIURI *aURL,
const char *aContentType,
const char *aCommand );
#else
NS_IMETHOD HandleUnknownContentType(nsIDocumentLoader* loader,
nsIChannel* channel,
const char *aContentType,
const char *aCommand );
#endif // NECKO
protected:
nsIDOMWindow *mToolbarWindow; // weak reference
nsIDOMWindow *mContentWindow; // weak reference
nsIWebShellWindow *mWebShellWin; // weak reference
nsIWebShell *mWebShell; // weak reference
nsIWebShell *mContentAreaWebShell; // weak reference
typedef enum {
eUninitializedEditorType = 0,
ePlainTextEditorType = 1,
eHTMLTextEditorType = 2
} EEditorType;
nsIPresShell* GetPresShellFor(nsIWebShell* aWebShell);
NS_IMETHOD DoEditorMode(nsIWebShell *aWebShell);
NS_IMETHOD ExecuteScript(nsIScriptContext * aContext, const nsString& aScript);
NS_IMETHOD InstantiateEditor(nsIDOMDocument *aDoc, nsIPresShell *aPresShell);
NS_IMETHOD TransferDocumentStateListeners();
NS_IMETHOD RemoveOneProperty(const nsString& aProp, const nsString& aAttr);
void SetButtonImage(nsIDOMNode * aParentNode, PRInt32 aBtnNum, const nsString &aResName);
NS_IMETHOD CreateWindowWithURL(const char* urlStr);
NS_IMETHOD PrepareDocumentForEditing(nsIURI *aUrl);
NS_IMETHOD DoFind(PRBool aFindNext);
// this returns an AddReffed nsIScriptContext. You must relase it.
nsIScriptContext* GetScriptContext(nsIDOMWindow * aWin);
nsString mEnableScript;
nsString mDisableScript;
EEditorType mEditorType;
nsString mEditorTypeString; // string which describes which editor type will be instantiated (lowercased)
nsCOMPtr<nsIHighLevelHTMLEditor> mEditor; // this can be either an HTML or plain text (or other?) editor
nsCOMPtr<nsISupports> mSearchContext; // context used for search and replace. Owned by the appshell.
nsInterfaceState* mStateMaintainer; // we hold the owning ref to this.
PRInt32 mWrapColumn; // can't actually set this 'til the editor is created, so we may have to hold on to it for a while
nsCOMPtr<nsISpellChecker> mSpellChecker;
nsStringArray mSuggestedWordList;
PRInt32 mSuggestedWordIndex;
NS_IMETHOD DeleteSuggestedWordList();
nsStringArray mDictionaryList;
PRInt32 mDictionaryIndex;
// this is a holding pen for doc state listeners. They will be registered with
// the editor when that gets created.
nsCOMPtr<nsISupportsArray> mDocStateListeners; // contents are nsISupports
};
#endif // nsEditorShell_h___

View File

@@ -0,0 +1,212 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is Mozilla Communicator client code.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are Copyright (C) 1998
* Netscape Communications Corporation. All Rights Reserved.
*/
#include "nsEditorShellFactory.h"
#include "nsEditorShell.h"
#include "nsEditor.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsXPComFactory.h"
static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID);
static NS_DEFINE_IID(kIFactoryIID, NS_IFACTORY_IID);
static NS_DEFINE_CID(kComponentManagerCID, NS_COMPONENTMANAGER_CID);
static NS_DEFINE_IID(kEditorShellCID, NS_EDITORSHELL_CID);
/////////////////////////////////////////////////////////////////////////
// nsEditorShellFactoryImpl
/////////////////////////////////////////////////////////////////////////
nsEditorShellFactoryImpl::nsEditorShellFactoryImpl(const nsCID &aClass,
const char* className,
const char* progID)
: mClassID(aClass), mClassName(className), mProgID(progID)
{
NS_INIT_REFCNT();
}
nsEditorShellFactoryImpl::~nsEditorShellFactoryImpl(void)
{
NS_ASSERTION(mRefCnt == 0, "non-zero refcnt at destruction");
}
NS_IMETHODIMP
nsEditorShellFactoryImpl::QueryInterface(REFNSIID aIID,void** aInstancePtr)
{
if (aInstancePtr == NULL)
{
return NS_ERROR_NULL_POINTER;
}
// Always NULL result, in case of failure
*aInstancePtr = NULL;
if ( aIID.Equals(kISupportsIID) )
{
*aInstancePtr = NS_STATIC_CAST(nsISupports*, this);
}
else if ( aIID.Equals(kIFactoryIID) )
{
*aInstancePtr = NS_STATIC_CAST(nsIFactory*, this);
}
if (*aInstancePtr == NULL)
{
return NS_ERROR_NO_INTERFACE;
}
AddRef();
return NS_OK;
}
NS_IMPL_ADDREF(nsEditorShellFactoryImpl)
NS_IMPL_RELEASE(nsEditorShellFactoryImpl)
NS_IMETHODIMP
nsEditorShellFactoryImpl::CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (!aResult)
return NS_ERROR_NULL_POINTER;
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
*aResult = NULL;
nsresult rv;
nsISupports *inst = nsnull;
if (mClassID.Equals(kEditorShellCID)) {
if (NS_FAILED(rv = NS_NewEditorShell((nsIEditorShell**) &inst)))
return rv;
}
else {
return NS_ERROR_NO_INTERFACE;
}
if (NS_FAILED(rv = inst->QueryInterface(aIID, aResult))) {
// We didn't get the right interface.
NS_ERROR("didn't support the interface you wanted");
}
NS_IF_RELEASE(inst);
return rv;
}
NS_IMETHODIMP
nsEditorShellFactoryImpl::LockFactory(PRBool aLock)
{
// Not implemented in simplest case.
return NS_OK;
}
nsresult
GetEditorShellFactory(nsIFactory **aFactory, const nsCID &aClass, const char *aClassName, const char *aProgID)
{
PR_EnterMonitor(GetEditorMonitor());
nsEditorShellFactoryImpl* factory = new nsEditorShellFactoryImpl(aClass, aClassName, aProgID);
if (!factory)
return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsIFactory> pNSIFactory (do_QueryInterface(factory));
if (!pNSIFactory)
return NS_ERROR_NO_INTERFACE;
nsresult result = pNSIFactory->QueryInterface(kIFactoryIID,
(void **)aFactory);
PR_ExitMonitor(GetEditorMonitor());
return result;
}
//#define EDITOR_SHELL_STANDALONE
#if EDITOR_SHELL_STANDALONE
// return the proper factory to the caller
extern "C" PR_IMPLEMENT(nsresult)
NSGetFactory(nsISupports* aServMgr,
const nsCID &aClass,
const char *aClassName,
const char *aProgID,
nsIFactory **aFactory)
{
if (! aFactory)
return NS_ERROR_NULL_POINTER;
nsEditorShellFactoryImpl* factory = new nsEditorShellFactoryImpl(aClass, aClassName, aProgID);
if (factory == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(factory);
*aFactory = factory;
return NS_OK;
}
extern "C" PR_IMPLEMENT(nsresult)
NSRegisterSelf(nsISupports* aServMgr , const char* aPath)
{
nsresult rv;
nsCOMPtr<nsIServiceManager> servMgr(do_QueryInterface(aServMgr, &rv));
if (NS_FAILED(rv)) return rv;
NS_WITH_SERVICE(nsIComponentManager, compMgr, kComponentManagerCID, &rv);
if (NS_FAILED(rv)) return rv;
rv = compMgr->RegisterComponent(kEditorAppCoreCID,
"Editor Shell Component",
"component://netscape/editor/editorshell",
aPath, PR_TRUE, PR_TRUE);
if (NS_FAILED(rv)) return rv;
return NS_OK;
}
extern "C" PR_IMPLEMENT(nsresult)
NSUnregisterSelf(nsISupports* aServMgr, const char* aPath)
{
nsresult rv;
nsCOMPtr<nsIServiceManager> servMgr(do_QueryInterface(aServMgr, &rv));
if (NS_FAILED(rv)) return rv;
NS_WITH_SERVICE(nsIComponentManager, compMgr, kComponentManagerCID, &rv);
if (NS_FAILED(rv)) return rv;
rv = compMgr->UnregisterComponent(kEditorAppCoreCID, aPath);
if (NS_FAILED(rv)) return rv;
return NS_OK;
}
#endif

View File

@@ -0,0 +1,60 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsEditorAppCoreFactory_h___
#define nsEditorAppCoreFactory_h___
//#include "nscore.h"
//#include "nsString.h"
#include "nsIFactory.h"
#include "nsISupports.h"
////////////////////////////////////////////////////////////////////////////////
// nsEditorAppCoreFactory:
////////////////////////////////////////////////////////////////////////////////
class nsEditorShellFactoryImpl : public nsIFactory
{
public:
nsEditorShellFactoryImpl(const nsCID &aClass, const char* className, const char* progID);
// nsISupports methods
NS_DECL_ISUPPORTS
PRBool CanUnload(void);
NS_IMETHOD CreateInstance(nsISupports *aOuter,
const nsIID& aIID,
void **aResult);
NS_IMETHOD LockFactory(PRBool aLock);
protected:
virtual ~nsEditorShellFactoryImpl();
protected:
nsCID mClassID;
const char* mClassName;
const char* mProgID;
};
nsresult
GetEditorShellFactory(nsIFactory **aFactory, const nsCID &aClass, const char *aClassName, const char *aProgID);
#endif // nsEditorAppCoreFactory_h___

View File

@@ -0,0 +1,52 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsEditorUtils.h"
/******************************************************************************
* nsAutoSelectionReset
*****************************************************************************/
nsAutoSelectionReset::nsAutoSelectionReset(nsIDOMSelection *aSel)
{
mInitialized = PR_FALSE;
mSel = do_QueryInterface(aSel);
if (mSel)
{
mSel->GetAnchorNode(getter_AddRefs(mStartNode));
mSel->GetAnchorOffset(&mStartOffset);
mSel->GetFocusNode(getter_AddRefs(mEndNode));
mSel->GetFocusOffset(&mEndOffset);
if (mStartNode && mEndNode)
mInitialized = PR_TRUE;
}
}
nsAutoSelectionReset::~nsAutoSelectionReset()
{
if (mSel && mInitialized)
{
// restore original selection
mSel->Collapse(mStartNode, mStartOffset);
mSel->Extend(mEndNode, mEndOffset);
}
}

View File

@@ -0,0 +1,62 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsEditorUtils_h__
#define nsEditorUtils_h__
#include "nsCOMPtr.h"
#include "nsIDOMNode.h"
#include "nsIDOMSelection.h"
#include "nsIEditor.h"
class nsAutoEditBatch
{
private:
nsCOMPtr<nsIEditor> mEd;
public:
nsAutoEditBatch( nsIEditor *aEd) : mEd(do_QueryInterface(aEd))
{ if (mEd) mEd->BeginTransaction(); }
~nsAutoEditBatch() { if (mEd) mEd->EndTransaction(); }
};
class nsAutoSelectionReset
{
private:
/** ref-counted reference to the selection that we are supposed to restore */
nsCOMPtr<nsIDOMSelection> mSel;
/** PR_TRUE if this instance initialized itself correctly */
PRBool mInitialized;
nsCOMPtr<nsIDOMNode> mStartNode;
nsCOMPtr<nsIDOMNode> mEndNode;
PRInt32 mStartOffset;
PRInt32 mEndOffset;
public:
/** constructor responsible for remembering all state needed to restore aSel */
nsAutoSelectionReset(nsIDOMSelection *aSel);
/** destructor restores mSel to its former state */
~nsAutoSelectionReset();
};
#endif // nsEditorUtils_h__

View File

@@ -0,0 +1,132 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1999 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsHTMLEditFactory.h"
#include "nsIHTMLEditor.h"
#include "nsHTMLEditor.h"
#include "nsEditor.h"
#include "nsEditorCID.h"
#include "nsIComponentManager.h"
static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID);
static NS_DEFINE_IID(kIFactoryIID, NS_IFACTORY_IID);
static NS_DEFINE_IID(kIHTMLEditorIID, NS_IHTMLEDITOR_IID);
static NS_DEFINE_IID(kHTMLEditorCID, NS_HTMLEDITOR_CID);
static NS_DEFINE_IID(kIHTMLEditFactoryIID, NS_IHTMLEDITORFACTORY_IID);
nsresult
GetHTMLEditFactory(nsIFactory **aFactory, const nsCID & aClass)
{
PR_EnterMonitor(GetEditorMonitor());
nsHTMLEditFactory *factory = new nsHTMLEditFactory(aClass);
if (!factory)
return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsIFactory> pNSIFactory = do_QueryInterface(factory);
if (!pNSIFactory)
return NS_ERROR_NO_INTERFACE;
nsresult result = pNSIFactory->QueryInterface(kIFactoryIID,
(void **)aFactory);
PR_ExitMonitor(GetEditorMonitor());
return result;
}
////////////////////////////////////////////////////////////////////////////
// from nsISupports
NS_IMETHODIMP
nsHTMLEditFactory::QueryInterface(const nsIID& aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
NS_NOTREACHED("!nsEditor");
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(kIFactoryIID) ||
aIID.Equals(kISupportsIID)) {
*aInstancePtr = (void*) this;
AddRef();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMPL_ADDREF(nsHTMLEditFactory)
NS_IMPL_RELEASE(nsHTMLEditFactory)
////////////////////////////////////////////////////////////////////////////
// from nsIFactory:
NS_IMETHODIMP
nsHTMLEditFactory::CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
*aResult = nsnull;
nsISupports *obj = nsnull;
if (!aResult)
return NS_ERROR_NULL_POINTER;
if (aOuter && !aIID.Equals(kISupportsIID))
return NS_NOINTERFACE; // XXX right error?
if (mCID.Equals(kHTMLEditorCID))
{
//Need to cast to interface first to avoid "ambiguous conversion..." error
// because of multiple nsISupports in the class hierarchy
obj = (nsISupports *)(nsIHTMLEditor*)new nsHTMLEditor();
}
//more class ids to support. here
if (obj && NS_FAILED(obj->QueryInterface(aIID, (void**)aResult)) )
{
delete obj;
return NS_NOINTERFACE;
}
return NS_OK;
}
NS_IMETHODIMP
nsHTMLEditFactory::LockFactory(PRBool aLock)
{
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////
nsHTMLEditFactory::nsHTMLEditFactory(const nsCID &aClass)
:mCID(aClass)
{
NS_INIT_REFCNT();
}
nsHTMLEditFactory::~nsHTMLEditFactory()
{
//nsComponentManager::UnregisterFactory(mCID, (nsIFactory *)this); //we are out of ref counts anyway
}

View File

@@ -0,0 +1,66 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1999 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsHTMLEditFactory_h___
#define nsHTMLEditFactory_h___
#include "nsISupports.h"
#include "nsIFactory.h"
/*
Factory that can make a text editor
*/
/**
* This supplies the neccessary entrance to the edit module. it will return any
* instantiations that we need.
*/
class nsHTMLEditFactory;
extern nsresult GetHTMLEditFactory(nsIFactory **aFactory, const nsCID & aClass);
class nsHTMLEditFactory : public nsIFactory {
public:
////////////////////////////////////////////////////////////////////////////
// from nsISupports and AggregatedQueryInterface:
NS_DECL_ISUPPORTS
////////////////////////////////////////////////////////////////////////////
// from nsIFactory:
NS_IMETHOD
CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult);
NS_IMETHOD
LockFactory(PRBool aLock);
////////////////////////////////////////////////////////////////////////////
virtual ~nsHTMLEditFactory(void);
private:
nsHTMLEditFactory(const nsCID &aClass); //will fill the aFactory with the result from queryinterface
/** GetHTMLEditFactory
* creates an edit factory other CSID supported friend functions here.
*/
friend nsresult GetHTMLEditFactory(nsIFactory **, const nsCID & );
const nsCID &mCID;
};
#endif //nsIEditFactory_h___

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,115 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsHTMLEditRules_h__
#define nsHTMLEditRules_h__
#include "nsTextEditRules.h"
#include "nsISupportsArray.h"
#include "nsCOMPtr.h"
class nsISupportsArray;
class nsVoidArray;
class nsHTMLEditRules : public nsTextEditRules
{
public:
nsHTMLEditRules(PRUint32 aFlags);
virtual ~nsHTMLEditRules();
// nsEditRules methods
NS_IMETHOD WillDoAction(nsIDOMSelection *aSelection, nsRulesInfo *aInfo, PRBool *aCancel);
NS_IMETHOD DidDoAction(nsIDOMSelection *aSelection, nsRulesInfo *aInfo, nsresult aResult);
protected:
enum IterDirection
{
kIterForward,
kIterBackward
};
enum RulesEndpoint
{
kStart,
kEnd
};
// nsHTMLEditRules implementation methods
nsresult WillInsertText(nsIDOMSelection *aSelection,
PRBool *aCancel,
PlaceholderTxn **aTxn,
const nsString *inString,
nsString *outString,
TypeInState typeInState,
PRInt32 aMaxLength);
nsresult WillInsertBreak(nsIDOMSelection *aSelection, PRBool *aCancel);
nsresult WillDeleteSelection(nsIDOMSelection *aSelection, nsIEditor::ESelectionCollapseDirection aAction, PRBool *aCancel);
nsresult WillMakeList(nsIDOMSelection *aSelection, PRBool aOrderd, PRBool *aCancel);
nsresult WillIndent(nsIDOMSelection *aSelection, PRBool *aCancel);
nsresult WillOutdent(nsIDOMSelection *aSelection, PRBool *aCancel);
nsresult WillAlign(nsIDOMSelection *aSelection, const nsString *alignType, PRBool *aCancel);
nsresult WillMakeHeader(nsIDOMSelection *aSelection, PRBool *aCancel);
nsresult WillMakeAddress(nsIDOMSelection *aSelection, PRBool *aCancel);
nsresult WillMakePRE(nsIDOMSelection *aSelection, PRBool *aCancel);
nsresult InsertTab(nsIDOMSelection *aSelection, PRBool *aCancel, PlaceholderTxn **aTxn, nsString *outString);
nsresult InsertSpace(nsIDOMSelection *aSelection, PRBool *aCancel, PlaceholderTxn **aTxn, nsString *outString);
nsresult ReturnInHeader(nsIDOMSelection *aSelection, nsIDOMNode *aHeader, nsIDOMNode *aTextNode, PRInt32 aOffset);
nsresult ReturnInParagraph(nsIDOMSelection *aSelection, nsIDOMNode *aHeader, nsIDOMNode *aTextNode, PRInt32 aOffset, PRBool *aCancel);
nsresult ReturnInListItem(nsIDOMSelection *aSelection, nsIDOMNode *aHeader, nsIDOMNode *aTextNode, PRInt32 aOffset);
// helper methods
static nsresult GetTabAsNBSPs(nsString *outString);
static nsresult GetTabAsNBSPsAndSpace(nsString *outString);
static PRBool IsHeader(nsIDOMNode *aNode);
static PRBool IsParagraph(nsIDOMNode *aNode);
static PRBool IsListItem(nsIDOMNode *aNode);
static PRBool IsUnorderedList(nsIDOMNode *aNode);
static PRBool IsOrderedList(nsIDOMNode *aNode);
static PRBool IsBreak(nsIDOMNode *aNode);
static PRBool IsBody(nsIDOMNode *aNode);
static PRBool IsBlockquote(nsIDOMNode *aNode);
static PRBool IsDiv(nsIDOMNode *aNode);
PRBool IsFirstNode(nsIDOMNode *aNode);
PRBool IsLastNode(nsIDOMNode *aNode);
nsresult GetPromotedPoint(RulesEndpoint aWhere, nsIDOMNode *aNode, PRInt32 aOffset,
PRInt32 actionID, nsCOMPtr<nsIDOMNode> *outNode, PRInt32 *outOffset);
nsresult GetPromotedRanges(nsIDOMSelection *inSelection,
nsCOMPtr<nsISupportsArray> *outArrayOfRanges,
PRInt32 inOperationType);
static nsresult GetNodesForOperation(nsISupportsArray *inArrayOfRanges,
nsCOMPtr<nsISupportsArray> *outArrayOfNodes,
PRInt32 inOperationType);
static nsresult MakeTransitionList(nsISupportsArray *inArrayOfNodes,
nsVoidArray *inTransitionArray);
nsresult ReplaceContainer(nsIDOMNode *inNode, nsCOMPtr<nsIDOMNode> *outNode, nsString &aNodeType);
nsresult RemoveContainer(nsIDOMNode *inNode);
nsresult InsertContainerAbove(nsIDOMNode *inNode, nsCOMPtr<nsIDOMNode> *outNode, nsString &aNodeType);
};
#endif //nsHTMLEditRules_h__

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,434 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsHTMLEditor_h__
#define nsHTMLEditor_h__
#include "nsCOMPtr.h"
#include "nsIHighLevelHTMLEditor.h"
#include "nsITableEditor.h"
#include "nsIEditorMailSupport.h"
#include "nsIEditorStyleSheets.h"
#include "nsEditor.h"
#include "nsIDOMElement.h"
#include "nsIDOMEventListener.h"
#include "nsITableLayout.h"
#include "TypeInState.h"
#include "nsEditRules.h"
/**
* The HTML editor implementation.<br>
* Use to edit HTML document represented as a DOM tree.
*/
class nsHTMLEditor : public nsEditor,
public nsIHighLevelHTMLEditor,
public nsIEditorMailSupport,
public nsITableEditor,
public nsIEditorStyleSheets
{
typedef enum {eNoOp, eReplaceParent=1, eInsertParent=2} BlockTransformationType;
public:
// see nsIHTMLEditor for documentation
//Interfaces for addref and release and queryinterface
//NOTE macro used is for classes that inherit from
// another class. Only the base class should use NS_DECL_ISUPPORTS
NS_DECL_ISUPPORTS_INHERITED
nsHTMLEditor();
virtual ~nsHTMLEditor();
/* ------------ nsIHighLevelHTMLEditor methods -------------- */
NS_IMETHOD GetDocumentLength(PRInt32 *aCount);
NS_IMETHOD SetMaxTextLength(PRInt32 aMaxTextLength);
NS_IMETHOD GetMaxTextLength(PRInt32& aMaxTextLength);
NS_IMETHOD SetInlineProperty(nsIAtom *aProperty,
const nsString *aAttribute,
const nsString *aValue);
NS_IMETHOD GetInlineProperty(nsIAtom *aProperty,
const nsString *aAttribute,
const nsString *aValue,
PRBool &aFirst, PRBool &aAny, PRBool &aAll);
NS_IMETHOD RemoveInlineProperty(nsIAtom *aProperty, const nsString *aAttribute);
NS_IMETHOD InsertBreak();
NS_IMETHOD InsertText(const nsString& aStringToInsert);
NS_IMETHOD InsertHTML(const nsString &aInputString);
NS_IMETHOD InsertElement(nsIDOMElement* aElement, PRBool aDeleteSelection);
NS_IMETHOD DeleteSelection(ESelectionCollapseDirection aAction);
NS_IMETHOD DeleteSelectionAndCreateNode(const nsString& aTag, nsIDOMNode ** aNewNode);
NS_IMETHOD SelectElement(nsIDOMElement* aElement);
NS_IMETHOD SetCaretAfterElement(nsIDOMElement* aElement);
NS_IMETHOD GetParagraphFormat(nsString& aParagraphFormat);
NS_IMETHOD SetParagraphFormat(const nsString& aParagraphFormat);
NS_IMETHOD GetParagraphStyle(nsStringArray *aTagList);
NS_IMETHOD RemoveParagraphStyle();
NS_IMETHOD AddBlockParent(nsString& aParentTag);
NS_IMETHOD ReplaceBlockParent(nsString& aParentTag);
NS_IMETHOD RemoveParent(const nsString &aParentTag);
NS_IMETHOD InsertList(const nsString& aListType);
NS_IMETHOD Indent(const nsString& aIndent);
NS_IMETHOD Align(const nsString& aAlign);
NS_IMETHOD GetElementOrParentByTagName(const nsString& aTagName, nsIDOMNode *aNode, nsIDOMElement** aReturn);
NS_IMETHOD GetSelectedElement(const nsString& aTagName, nsIDOMElement** aReturn);
NS_IMETHOD CreateElementWithDefaults(const nsString& aTagName, nsIDOMElement** aReturn);
NS_IMETHOD SaveHLineSettings(nsIDOMElement* aElement);
NS_IMETHOD InsertLinkAroundSelection(nsIDOMElement* aAnchorElement);
/* ------------ nsIEditorStyleSheets methods -------------- */
NS_IMETHOD ApplyStyleSheet(const nsString& aURL);
NS_IMETHOD AddStyleSheet(nsICSSStyleSheet* aSheet);
NS_IMETHOD RemoveStyleSheet(nsICSSStyleSheet* aSheet);
/* ------------ nsIEditorMailSupport methods -------------- */
NS_IMETHOD GetBodyWrapWidth(PRInt32 *aWrapColumn);
NS_IMETHOD SetBodyWrapWidth(PRInt32 aWrapColumn);
NS_IMETHOD PasteAsQuotation();
NS_IMETHOD InsertAsQuotation(const nsString& aQuotedText);
NS_IMETHOD PasteAsCitedQuotation(const nsString& aCitation);
NS_IMETHOD InsertAsCitedQuotation(const nsString& aQuotedText, const nsString& aCitation);
NS_IMETHOD GetEmbeddedObjects(nsISupportsArray** aNodeList);
/* ------------ nsITableEditor methods -------------- */
NS_IMETHOD InsertTable();
NS_IMETHOD InsertTableCell(PRInt32 aNumber, PRBool aAfter);
NS_IMETHOD InsertTableColumn(PRInt32 aNumber, PRBool aAfter);
NS_IMETHOD InsertTableRow(PRInt32 aNumber, PRBool aAfter);
NS_IMETHOD DeleteTable();
NS_IMETHOD DeleteTableCell(PRInt32 aNumber);
NS_IMETHOD DeleteTableColumn(PRInt32 aNumber);
NS_IMETHOD DeleteTableRow(PRInt32 aNumber);
NS_IMETHOD JoinTableCells(PRBool aCellToRight);
NS_IMETHOD NormalizeTable(nsIDOMElement *aTable);
NS_IMETHOD GetCellIndexes(nsIDOMElement *aCell, PRInt32& aRowIndex, PRInt32& aColIndex);
NS_IMETHOD GetTableSize(nsIDOMElement *aTable, PRInt32& aRowCount, PRInt32& aColCount);
NS_IMETHOD GetCellAt(nsIDOMElement* aTable, PRInt32 aRowIndex, PRInt32 aColIndex, nsIDOMElement* &aCell);
NS_IMETHOD GetCellDataAt(nsIDOMElement* aTable, PRInt32 aRowIndex, PRInt32 aColIndex, nsIDOMElement* &aCell,
PRInt32& aStartRowIndex, PRInt32& aStartColIndex,
PRInt32& aRowSpan, PRInt32& aColSpan, PRBool& aIsSelected);
// Selection and navigation
/* obsolete
NS_IMETHOD MoveSelectionUp(nsIAtom *aIncrement, PRBool aExtendSelection);
NS_IMETHOD MoveSelectionDown(nsIAtom *aIncrement, PRBool aExtendSelection);
NS_IMETHOD MoveSelectionNext(nsIAtom *aIncrement, PRBool aExtendSelection);
NS_IMETHOD MoveSelectionPrevious(nsIAtom *aIncrement, PRBool aExtendSelection);
NS_IMETHOD SelectNext(nsIAtom *aIncrement, PRBool aExtendSelection);
NS_IMETHOD SelectPrevious(nsIAtom *aIncrement, PRBool aExtendSelection);
NS_IMETHOD ScrollUp(nsIAtom *aIncrement);
NS_IMETHOD ScrollDown(nsIAtom *aIncrement);
NS_IMETHOD ScrollIntoView(PRBool aScrollToBegin);
*/
/* miscellaneous */
// This sets background on the appropriate container element (table, cell,)
// or calls into nsTextEditor to set the page background
NS_IMETHOD SetBackgroundColor(const nsString& aColor);
NS_IMETHOD SetBodyAttribute(const nsString& aAttr, const nsString& aValue);
/* ------------ Overrides of nsEditor interface methods -------------- */
NS_IMETHOD Init(nsIDOMDocument *aDoc, nsIPresShell *aPresShell, PRUint32 aFlags);
NS_IMETHOD GetFlags(PRUint32 *aFlags);
NS_IMETHOD SetFlags(PRUint32 aFlags);
NS_IMETHOD Cut();
NS_IMETHOD Copy();
NS_IMETHOD Paste();
NS_IMETHOD OutputToString(nsString& aOutputString,
const nsString& aFormatType,
PRUint32 aFlags);
NS_IMETHOD OutputToStream(nsIOutputStream* aOutputStream,
const nsString& aFormatType,
const nsString* aCharsetOverride,
PRUint32 aFlags);
NS_IMETHOD DebugUnitTests(PRInt32 *outNumTests, PRInt32 *outNumTestsFailed);
protected:
virtual void InitRules();
NS_IMETHOD GetLayoutObject(nsIDOMNode *aNode, nsISupports **aLayoutObject);
NS_IMETHOD DeleteSelectionAndPrepareToCreateNode(nsCOMPtr<nsIDOMNode> &parentSelectedNode, PRInt32& offsetOfNewNode);
/* StyleSheet load callback */
static void ApplyStyleSheetToPresShellDocument(nsICSSStyleSheet* aSheet, void *aData);
/* remove the old style sheet, and apply the supplied one */
NS_IMETHOD ReplaceStyleSheet(nsICSSStyleSheet *aNewSheet);
// Return TRUE if aElement is a table-related elemet and caret was set
PRBool SetCaretInTableCell(nsIDOMElement* aElement);
PRBool IsElementInBody(nsIDOMElement* aElement);
// Table Editing (implemented in EditTable.cpp)
// Helper used to get nsITableLayout interface for methods implemented in nsTableFrame
NS_IMETHOD GetTableLayoutObject(nsIDOMElement* aTable, nsITableLayout **tableLayoutObject);
// Table utilities
// All of the above need to get the same basic context data
NS_IMETHOD GetCellContext(nsCOMPtr<nsIDOMSelection> &aSelection,
nsCOMPtr<nsIDOMElement> &aTable, nsCOMPtr<nsIDOMElement> &aCell,
nsCOMPtr<nsIDOMNode> &aCellParent, PRInt32& aCellOffset,
PRInt32& aRow, PRInt32& aCol);
// Setting caret to a logical place can get tricky,
// especially after deleting table stuff
typedef enum { ePreviousColumn, ePreviousRow } SetCaretSearchDirection;
NS_IMETHOD SetCaretAfterTableEdit(nsIDOMElement* aTable, PRInt32 aCol, PRInt32 aRow, SetCaretSearchDirection aDirection);
NS_IMETHOD ReParentContentOfNode(nsIDOMNode *aNode,
nsString &aParentTag,
BlockTransformationType aTranformation);
NS_IMETHOD ReParentBlockContent(nsIDOMNode *aNode,
nsString &aParentTag,
nsIDOMNode *aBlockParentNode,
nsString &aBlockParentTag,
BlockTransformationType aTranformation,
nsIDOMNode **aNewParentNode);
NS_IMETHOD ReParentContentOfRange(nsIDOMRange *aRange,
nsString &aParentTag,
BlockTransformationType aTranformation);
NS_IMETHOD RemoveParagraphStyleFromRange(nsIDOMRange *aRange);
NS_IMETHOD RemoveParagraphStyleFromBlockContent(nsIDOMRange *aRange);
NS_IMETHOD RemoveParentFromRange(const nsString &aParentTag, nsIDOMRange *aRange);
NS_IMETHOD RemoveParentFromBlockContent(const nsString &aParentTag, nsIDOMRange *aRange);
NS_IMETHOD IsRootTag(nsString &aTag, PRBool &aIsTag);
NS_IMETHOD IsSubordinateBlock(nsString &aTag, PRBool &aIsTag);
/** content-based query returns PR_TRUE if <aProperty aAttribute=aValue> effects aNode
* If <aProperty aAttribute=aValue> contains aNode,
* but <aProperty aAttribute=SomeOtherValue> also contains aNode and the second is
* more deeply nested than the first, then the first does not effect aNode.
*
* @param aNode The target of the query
* @param aProperty The property that we are querying for
* @param aAttribute The attribute of aProperty, example: color in <FONT color="blue">
* May be null.
* @param aValue The value of aAttribute, example: blue in <FONT color="blue">
* May be null. Ignored if aAttribute is null.
* @param aIsSet [OUT] PR_TRUE if <aProperty aAttribute=aValue> effects aNode.
* @param aStyleNode [OUT] set to the node representing <aProperty aAttribute=aValue>, if found.
* null if aIsSet is returned as PR_FALSE;
*/
virtual void IsTextPropertySetByContent(nsIDOMNode *aNode,
nsIAtom *aProperty,
const nsString *aAttribute,
const nsString *aValue,
PRBool &aIsSet,
nsIDOMNode **aStyleNode) const;
/** style-based query returns PR_TRUE if (aProperty, aAttribute) is set in aSC.
* WARNING: not well tested yet since we don't do style-based queries anywhere.
*/
virtual void IsTextStyleSet(nsIStyleContext *aSC,
nsIAtom *aProperty,
const nsString *aAttributes,
PRBool &aIsSet) const;
/** Moves the content between (aNode, aStartOffset) and (aNode, aEndOffset)
* into aNewParentNode, splitting aNode as necessary to maintain the relative
* position of all leaf content.
* @param aNode The node whose content we're repositioning.
* aNode can be either a text node or a container node.
* @param aNewParentNode The node that will be the repositioned contents' parent.
* The caller is responsible for allocating aNewParentNode
* @param aStartOffset The start offset of the content of aNode
* @param aEndOffset The end offset of the content of aNode.
*/
NS_IMETHOD MoveContentOfNodeIntoNewParent(nsIDOMNode *aNode,
nsIDOMNode *aNewParentNode,
PRInt32 aStartOffset,
PRInt32 aEndOffset);
/** Moves the content between (aStartNode, aStartOffset) and (aEndNode, aEndOffset)
* into aNewParentNode, splitting aStartNode and aEndNode as necessary to maintain
* the relative position of all leaf content.
* The content between the two endpoints MUST be "contiguous" in the sense that
* it is all in the same block. Another way of saying this is all content nodes
* between aStartNode and aEndNode must be inline.
* @see IntermediateNodesAreInline
*
* @param aStartNode The left node, can be either a text node or a container node.
* @param aStartOffset The start offset in the content of aStartNode
* @param aEndNode The right node, can be either a text node or a container node.
* @param aEndOffset The end offset in the content of aEndNode.
* @param aGrandParentNode The common ancestor of aStartNode and aEndNode.
* aGrandParentNode will be the parent of aNewParentNode.
* @param aNewParentNode The node that will be the repositioned contents' parent.
* The caller is responsible for allocating aNewParentNode
*/
NS_IMETHOD MoveContiguousContentIntoNewParent(nsIDOMNode *aStartNode,
PRInt32 aStartOffset,
nsIDOMNode *aEndNode,
PRInt32 aEndOffset,
nsIDOMNode *aGrandParentNode,
nsIDOMNode *aNewParentNode);
NS_IMETHOD SetTextPropertiesForNode(nsIDOMNode *aNode,
nsIDOMNode *aParent,
PRInt32 aStartOffset,
PRInt32 aEndOffset,
nsIAtom *aPropName,
const nsString *aAttribute,
const nsString *aValue);
NS_IMETHOD SetTextPropertiesForNodesWithSameParent(nsIDOMNode *aStartNode,
PRInt32 aStartOffset,
nsIDOMNode *aEndNode,
PRInt32 aEndOffset,
nsIDOMNode *aParent,
nsIAtom *aPropName,
const nsString *aAttribute,
const nsString *aValue);
NS_IMETHOD SetTextPropertiesForNodeWithDifferentParents(nsIDOMRange *aRange,
nsIDOMNode *aStartNode,
PRInt32 aStartOffset,
nsIDOMNode *aEndNode,
PRInt32 aEndOffset,
nsIDOMNode *aParent,
nsIAtom *aPropName,
const nsString *aAttribute,
const nsString *aValue);
NS_IMETHOD RemoveTextPropertiesForNode(nsIDOMNode *aNode,
nsIDOMNode *aParent,
PRInt32 aStartOffset,
PRInt32 aEndOffset,
nsIAtom *aPropName,
const nsString *aAttribute);
NS_IMETHOD RemoveTextPropertiesForNodesWithSameParent(nsIDOMNode *aStartNode,
PRInt32 aStartOffset,
nsIDOMNode *aEndNode,
PRInt32 aEndOffset,
nsIDOMNode *aParent,
nsIAtom *aPropName,
const nsString *aAttribute);
NS_IMETHOD RemoveTextPropertiesForNodeWithDifferentParents(nsIDOMNode *aStartNode,
PRInt32 aStartOffset,
nsIDOMNode *aEndNode,
PRInt32 aEndOffset,
nsIDOMNode *aParent,
nsIAtom *aPropName,
const nsString *aAttribute);
NS_IMETHOD SetTypeInStateForProperty(TypeInState &aTypeInState,
nsIAtom *aPropName,
const nsString *aAttribute,
const nsString *aValue);
void GetTextSelectionOffsetsForRange(nsIDOMSelection *aSelection,
nsIDOMNode **aParent,
PRInt32 &aStartOffset,
PRInt32 &aEndOffset);
void ResetTextSelectionForRange(nsIDOMNode *aParent,
PRInt32 aStartOffset,
PRInt32 aEndOffset,
nsIDOMSelection *aSelection);
/** returns the absolute position of the end points of aSelection
* in the document as a text stream.
*/
nsresult GetTextSelectionOffsets(nsIDOMSelection *aSelection,
PRInt32 &aStartOffset,
PRInt32 &aEndOffset);
// Methods for handling plaintext quotations
NS_IMETHOD PasteAsPlaintextQuotation();
NS_IMETHOD InsertAsPlaintextQuotation(const nsString& aQuotedText);
// I hate seeing nsCOMPtr return types.
nsCOMPtr<nsIDOMElement> FindPreElement();
TypeInState *GetTypeInState();
/** simple utility to handle any error with event listener allocation or registration */
void HandleEventListenerError();
// Data members
protected:
TypeInState* mTypeInState;
nsEditRules* mRules;
nsCOMPtr<nsIDOMEventListener> mKeyListenerP;
nsCOMPtr<nsIDOMEventListener> mMouseListenerP;
nsCOMPtr<nsIDOMEventListener> mTextListenerP;
nsCOMPtr<nsIDOMEventListener> mCompositionListenerP;
nsCOMPtr<nsIDOMEventListener> mDragListenerP;
nsCOMPtr<nsIDOMEventListener> mFocusListenerP;
PRBool mIsComposing;
PRInt32 mMaxTextLength;
PRUint32 mWrapColumn;
// friends
friend class nsHTMLEditRules;
friend class nsTextEditRules;
};
#endif //nsHTMLEditor_h__

View File

@@ -0,0 +1,132 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef __nsIEditProperty_h__
#define __nsIEditProperty_h__
#include "nsISupports.h"
class nsIAtom;
class nsString;
#define NS_IEDITPROPERTY_IID \
{/* 9875cd40-ca81-11d2-8f4d-006008159b0c*/ \
0x9875cd40, 0xca81, 0x11d2, \
{0x8f, 0x4d, 0x0, 0x60, 0x8, 0x15, 0x9b, 0x0c} }
/** simple interface for describing a single property as it relates to a range of content.
*
*/
class nsIEditProperty : public nsISupports
{
public:
static const nsIID& GetIID() { static nsIID iid = NS_IEDITPROPERTY_IID; return iid; }
public:
/* we're still trying to decide how edit atoms will work. Until then, use these */
// XXX: fix ASAP!
// inline tags
static nsIAtom *b;
static nsIAtom *big;
static nsIAtom *i;
static nsIAtom *small;
static nsIAtom *strike;
static nsIAtom *sub;
static nsIAtom *sup;
static nsIAtom *tt;
static nsIAtom *u;
static nsIAtom *em;
static nsIAtom *strong;
static nsIAtom *dfn;
static nsIAtom *code;
static nsIAtom *samp;
static nsIAtom *kbd;
static nsIAtom *var;
static nsIAtom *cite;
static nsIAtom *abbr;
static nsIAtom *acronym;
static nsIAtom *font;
static nsIAtom *a;
static nsIAtom *img;
static nsIAtom *object;
static nsIAtom *br;
static nsIAtom *script;
static nsIAtom *map;
static nsIAtom *q;
static nsIAtom *span;
static nsIAtom *bdo;
static nsIAtom *input;
static nsIAtom *select;
static nsIAtom *textarea;
static nsIAtom *label;
static nsIAtom *button;
// Block tags
static nsIAtom *p;
static nsIAtom *div;
static nsIAtom *blockquote;
static nsIAtom *h1;
static nsIAtom *h2;
static nsIAtom *h3;
static nsIAtom *h4;
static nsIAtom *h5;
static nsIAtom *h6;
static nsIAtom *ul;
static nsIAtom *ol;
static nsIAtom *dl;
static nsIAtom *pre;
static nsIAtom *noscript;
static nsIAtom *form;
static nsIAtom *hr;
static nsIAtom *table;
static nsIAtom *fieldset;
static nsIAtom *address;
// Assumed to be block:
static nsIAtom *body;
static nsIAtom *tr;
static nsIAtom *td;
static nsIAtom *th;
static nsIAtom *caption;
static nsIAtom *col;
static nsIAtom *colgroup;
static nsIAtom *thead;
static nsIAtom *tfoot;
static nsIAtom *li;
static nsIAtom *dt;
static nsIAtom *dd;
static nsIAtom *legend;
/** properties **/
static nsIAtom *color;
static nsIAtom *face;
static nsIAtom *size;
/** special strings */
static nsString *allProperties; // this magic string represents the union of all inline style tags
// XXX: end temp code
};
extern nsresult NS_NewEditProperty(nsIEditProperty **aResult);
#endif

View File

@@ -0,0 +1,76 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsIEditorSupport_h__
#define nsIEditorSupport_h__
#include "nsISupports.h"
class nsIDOMNode;
/*
Private Editor interface for a class that can provide helper functions
*/
#define NS_IEDITORSUPPORT_IID \
{/* 89b999b0-c529-11d2-86da-000064657374*/ \
0x89b999b0, 0xc529, 0x11d2, \
{0x86, 0xda, 0x0, 0x0, 0x64, 0x65, 0x73, 0x74} }
/**
*/
class nsIEditorSupport : public nsISupports {
public:
static const nsIID& GetIID() { static nsIID iid = NS_IEDITORSUPPORT_IID; return iid; }
/**
* SplitNode() creates a new node identical to an existing node, and split the contents between the two nodes
* @param aExistingRightNode the node to split. It will become the new node's next sibling.
* @param aOffset the offset of aExistingRightNode's content|children to do the split at
* @param aNewLeftNode [OUT] the new node resulting from the split, becomes aExistingRightNode's previous sibling.
* @param aParent the parent of aExistingRightNode
*/
NS_IMETHOD SplitNodeImpl(nsIDOMNode * aExistingRightNode,
PRInt32 aOffset,
nsIDOMNode * aNewLeftNode,
nsIDOMNode * aParent)=0;
/**
* JoinNodes() takes 2 nodes and merge their content|children.
* @param aNodeToKeep The node that will remain after the join.
* @param aNodeToJoin The node that will be joined with aNodeToKeep.
* There is no requirement that the two nodes be of the same type.
* @param aParent The parent of aExistingRightNode
* @param aNodeToKeepIsFirst if PR_TRUE, the contents|children of aNodeToKeep come before the
* contents|children of aNodeToJoin, otherwise their positions are switched.
*/
NS_IMETHOD JoinNodesImpl(nsIDOMNode *aNodeToKeep,
nsIDOMNode *aNodeToJoin,
nsIDOMNode *aParent,
PRBool aNodeToKeepIsFirst)=0;
static nsresult GetChildOffset(nsIDOMNode *aChild, nsIDOMNode *aParent, PRInt32 &aOffset);
};
#endif //nsIEditorSupport_h__

View File

@@ -0,0 +1,124 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
// THIS FILE IS CURRENTLY THOUGHT TO BE OBSOLETE.
// KEEPING AROUND FOR A FEW DAYS JUST TO MAKE SURE;
// BUT IT'S NO LONGER PART OF THE BUILD.
#include "nsIDOMDocumentFragment.h"
#include "nsInsertHTMLTxn.h"
#include "nsIDOMSelection.h"
#include "nsIContent.h"
#include "nsIDOMNSRange.h"
nsInsertHTMLTxn::nsInsertHTMLTxn() : EditTxn(), mSrc("")
{
}
NS_IMETHODIMP nsInsertHTMLTxn::Init(const nsString& aSrc, nsIEditor* aEditor)
{
if (!aEditor)
return NS_ERROR_NULL_POINTER;
mSrc = aSrc;
mEditor = do_QueryInterface(aEditor);
return NS_OK;
}
nsInsertHTMLTxn::~nsInsertHTMLTxn()
{
//NS_RELEASE(mStr); // do nsStrings have to be released?
}
NS_IMETHODIMP nsInsertHTMLTxn::Do(void)
{
nsCOMPtr<nsIDOMSelection>selection;
nsresult res = mEditor->GetSelection(getter_AddRefs(selection));
if (NS_SUCCEEDED(res) && selection)
{
// Get the first range in the selection, and save it in mRange:
res = selection->GetRangeAt(0, getter_AddRefs(mRange));
if (NS_SUCCEEDED(res))
{
nsCOMPtr<nsIDOMNSRange> nsrange (do_QueryInterface(mRange));
if (nsrange)
{
#ifdef DEBUG_akkana
char* str = mSrc.ToNewCString();
printf("Calling nsInsertHTMLTxn::Do(%s)\n", str);
delete[] str;
#endif /* DEBUG_akkana */
nsCOMPtr<nsIDOMDocumentFragment> docfrag;
res = nsrange->CreateContextualFragment(mSrc, getter_AddRefs(docfrag));
// Now we have to insert that document fragment in an undoable way
printf("Sorry, Insert HTML not fully written yet\n");
return NS_ERROR_NOT_IMPLEMENTED;
}
}
#ifdef DEBUG_akkana
else printf("nsInsertHTMLTxn::Do: Couldn't get selection range!\n");
#endif
}
return res;
}
NS_IMETHODIMP nsInsertHTMLTxn::Undo(void)
{
#ifdef DEBUG_akkana
printf("%p Undo Insert HTML\n", this);
#endif /* DEBUG_akkana */
if (!mRange)
return NS_ERROR_NULL_POINTER;
return mRange->DeleteContents();
}
NS_IMETHODIMP nsInsertHTMLTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
if (nsnull != aDidMerge)
*aDidMerge=PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP nsInsertHTMLTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsInsertHTMLTxn::GetUndoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Remove HTML: ";
}
return NS_OK;
}
NS_IMETHODIMP nsInsertHTMLTxn::GetRedoString(nsString *aString)
{
if (nsnull!=aString)
{
*aString="Insert HTML: ";
}
return NS_OK;
}

View File

@@ -0,0 +1,82 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsInsertHTMLTxn_h__
#define nsInsertHTMLTxn_h__
#include "EditTxn.h"
#include "nsIEditor.h"
#include "nsIDOMRange.h"
#include "nsCOMPtr.h"
#define NS_INSERT_HTML_TXN_CID \
{/* a6cf90fd-15b3-11d2-932e-00805f8add3 */ \
0xa6cf90fc, 0x15b3, 0x11d2, \
{0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32} }
/**
* A transaction that inserts a string of html source
*/
class nsInsertHTMLTxn : public EditTxn
{
public:
static const nsIID& GetCID() { static nsIID iid = NS_INSERT_HTML_TXN_CID; return iid; }
/** initialize the transaction.
* @param aSrc the source for the HTML to insert
* @param aEditor the editor in which to do the work
*/
NS_IMETHOD Init(const nsString& aSrc,
nsIEditor *aEditor);
private:
nsInsertHTMLTxn();
public:
virtual ~nsInsertHTMLTxn();
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
protected:
/** the html to insert */
nsString mSrc;
/** the range representing the inserted fragment */
nsCOMPtr<nsIDOMRange> mRange;
/** the editor for this transaction */
nsCOMPtr<nsIEditor> mEditor;
friend class TransactionFactory;
};
#endif

View File

@@ -0,0 +1,300 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsCOMPtr.h"
#include "nsVoidArray.h"
#include "nsIContentViewer.h"
#include "nsIDocumentViewer.h"
#include "nsIDocument.h"
#include "nsIDOMDocument.h"
#include "nsIDOMXULDocument.h"
#include "nsIDiskDocument.h"
#include "nsIDOMElement.h"
#include "nsIDOMSelection.h"
#include "nsIEditor.h"
#include "nsIHighLevelHTMLEditor.h"
#include "nsInterfaceState.h"
nsInterfaceState::nsInterfaceState()
: mEditor(nsnull)
, mWebShell(nsnull)
, mBoldState(eStateUninitialized)
, mItalicState(eStateUninitialized)
, mUnderlineState(eStateUninitialized)
, mDirtyState(eStateUninitialized)
{
NS_INIT_REFCNT();
}
nsInterfaceState::~nsInterfaceState()
{
}
NS_IMPL_ADDREF(nsInterfaceState);
NS_IMPL_RELEASE(nsInterfaceState);
NS_IMETHODIMP
nsInterfaceState::QueryInterface(const nsIID& aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
return NS_ERROR_NULL_POINTER;
}
*aInstancePtr = nsnull;
if (aIID.Equals(nsIDOMSelectionListener::GetIID()))
{
*aInstancePtr = (void*)(nsIDOMSelectionListener*)this;
AddRef();
return NS_OK;
}
if (aIID.Equals(nsIDocumentStateListener::GetIID()))
{
*aInstancePtr = (void*)(nsIDocumentStateListener*)this;
AddRef();
return NS_OK;
}
if (aIID.Equals(nsCOMTypeInfo<nsISupports>::GetIID()))
{
*aInstancePtr = (void*)(nsISupports *)(nsIDOMSelectionListener*)this;
AddRef();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMETHODIMP
nsInterfaceState::Init(nsIHighLevelHTMLEditor* aEditor, nsIWebShell *aChromeWebShell)
{
if (!aEditor)
return NS_ERROR_INVALID_ARG;
if (!aChromeWebShell)
return NS_ERROR_INVALID_ARG;
mEditor = aEditor; // no addreffing here
mWebShell = aChromeWebShell;
return NS_OK;
}
NS_IMETHODIMP
nsInterfaceState::NotifyDocumentCreated()
{
return NS_OK;
}
NS_IMETHODIMP
nsInterfaceState::NotifyDocumentWillBeDestroyed()
{
return NS_OK;
}
NS_IMETHODIMP
nsInterfaceState::NotifyDocumentStateChanged(PRBool aNowDirty)
{
// update document modified. We should have some other notifications for this too.
return UpdateDirtyState(aNowDirty);
}
NS_IMETHODIMP
nsInterfaceState::NotifySelectionChanged()
{
nsresult rv;
// we don't really care if any of these fail.
// update bold
rv = UpdateTextState("b", "Editor:Style:IsBold", "bold", mBoldState);
// update italic
rv = UpdateTextState("i", "Editor:Style:IsItalic", "italic", mItalicState);
// update underline
rv = UpdateTextState("u", "Editor:Style:IsUnderline", "underline", mUnderlineState);
// udpate the font face
rv = UpdateFontFace("Editor:Font:Face", "font", mFontString);
// update the paragraph format popup
rv = UpdateParagraphState("Editor:Paragraph:Format", "format", mParagraphFormat);
// update the list buttons
rv = UpdateListState("Editor:Paragraph:List", "ol");
return NS_OK;
}
nsresult
nsInterfaceState::UpdateParagraphState(const char* observerName, const char* attributeName, nsString& ioParaFormat)
{
nsStringArray tagList;
mEditor->GetParagraphStyle(&tagList);
PRInt32 numTags = tagList.Count();
if (numTags > 0)
{
nsAutoString thisTag;
tagList.StringAt(0, thisTag);
if (thisTag != mParagraphFormat)
{
nsresult rv = SetNodeAttribute(observerName, attributeName, thisTag);
if (NS_FAILED(rv)) return rv;
mParagraphFormat = thisTag;
}
}
return NS_OK;
}
nsresult
nsInterfaceState::UpdateListState(const char* observerName, const char* tagName)
{
nsresult rv = NS_ERROR_NO_INTERFACE;
nsCOMPtr<nsIDOMSelection> domSelection;
{
nsCOMPtr<nsIEditor> editor = do_QueryInterface(mEditor);
editor->GetSelection(getter_AddRefs(domSelection));
}
nsAutoString tagStr(tagName);
nsCOMPtr<nsIDOMNode> domNode;
if (domSelection)
domSelection->GetAnchorNode(getter_AddRefs(domNode));
nsCOMPtr<nsIDOMElement> parentElement;
rv = mEditor->GetElementOrParentByTagName(tagStr, domNode, getter_AddRefs(parentElement));
return rv;
}
nsresult
nsInterfaceState::UpdateFontFace(const char* observerName, const char* attributeName, nsString& ioFontString)
{
nsresult rv;
PRBool firstOfSelectionHasProp = PR_FALSE;
PRBool anyOfSelectionHasProp = PR_FALSE;
PRBool allOfSelectionHasProp = PR_FALSE;
nsCOMPtr<nsIAtom> styleAtom = getter_AddRefs(NS_NewAtom("font"));
nsAutoString faceStr("face");
rv = mEditor->GetInlineProperty(styleAtom, &faceStr, nsnull, firstOfSelectionHasProp, anyOfSelectionHasProp, allOfSelectionHasProp);
return rv;
}
nsresult
nsInterfaceState::UpdateTextState(const char* tagName, const char* observerName, const char* attributeName, PRInt8& ioState)
{
nsresult rv;
PRBool firstOfSelectionHasProp = PR_FALSE;
PRBool anyOfSelectionHasProp = PR_FALSE;
PRBool allOfSelectionHasProp = PR_FALSE;
nsCOMPtr<nsIAtom> styleAtom = getter_AddRefs(NS_NewAtom(tagName));
rv = mEditor->GetInlineProperty(styleAtom, nsnull, nsnull, firstOfSelectionHasProp, anyOfSelectionHasProp, allOfSelectionHasProp);
PRBool &behaviour = allOfSelectionHasProp; // change this to alter the behaviour
if (behaviour != ioState)
{
rv = SetNodeAttribute(observerName, attributeName, behaviour ? "true" : "false");
if (NS_FAILED(rv))
return rv;
ioState = behaviour;
}
return rv;
}
nsresult
nsInterfaceState::UpdateDirtyState(PRBool aNowDirty)
{
if (mDirtyState != aNowDirty)
{
nsresult rv = SetNodeAttribute("Editor:Document:Dirty", "dirty", aNowDirty ? "true" : "false");
if (NS_FAILED(rv)) return rv;
mDirtyState = aNowDirty;
}
return NS_OK;
}
nsresult
nsInterfaceState::SetNodeAttribute(const char* nodeID, const char* attributeName, const nsString& newValue)
{
nsresult rv = NS_OK;
if (!mWebShell)
return NS_ERROR_NOT_INITIALIZED;
nsCOMPtr<nsIContentViewer> cv;
rv = mWebShell->GetContentViewer(getter_AddRefs(cv));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIDocumentViewer> docViewer = do_QueryInterface(cv, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIDocument> chromeDoc;
rv = docViewer->GetDocument(*getter_AddRefs(chromeDoc));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIDOMXULDocument> xulDoc = do_QueryInterface(chromeDoc, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIDOMElement> elem;
rv = xulDoc->GetElementById( nodeID, getter_AddRefs(elem) );
if (NS_FAILED(rv) || !elem) return rv;
return elem->SetAttribute(attributeName, newValue);
}
nsresult NS_NewInterfaceState(nsIHighLevelHTMLEditor* aEditor, nsIWebShell* aWebShell, nsIDOMSelectionListener** aInstancePtrResult)
{
nsInterfaceState* newThang = new nsInterfaceState;
if (!newThang)
return NS_ERROR_OUT_OF_MEMORY;
*aInstancePtrResult = nsnull;
nsresult rv = newThang->Init(aEditor, aWebShell);
if (NS_FAILED(rv))
{
delete newThang;
return rv;
}
return newThang->QueryInterface(nsIDOMSelectionListener::GetIID(), (void **)aInstancePtrResult);
}

View File

@@ -0,0 +1,90 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsInterfaceState_h__
#define nsInterfaceState_h__
#include "nsIDOMSelectionListener.h"
#include "nsIDocumentStateListener.h"
#include "nsIWebShell.h"
class nsIHighLevelHTMLEditor;
// class responsible for communicating changes in local state back to the UI.
// This is currently somewhat tied to a given XUL UI implementation
class nsInterfaceState : public nsIDOMSelectionListener,
public nsIDocumentStateListener
{
public:
nsInterfaceState();
virtual ~nsInterfaceState();
NS_DECL_ISUPPORTS
NS_IMETHOD Init(nsIHighLevelHTMLEditor* aEditor, nsIWebShell *aChromeWebShell);
// nsIDOMSelectionListener interface
NS_IMETHOD NotifySelectionChanged();
// nsIDocumentStateListener interface
NS_IMETHOD NotifyDocumentCreated();
NS_IMETHOD NotifyDocumentWillBeDestroyed();
NS_IMETHOD NotifyDocumentStateChanged(PRBool aNowDirty);
protected:
enum {
eStateUninitialized = -1,
eStateOff = PR_FALSE,
eStateOn = PR_TRUE
};
nsresult SetNodeAttribute(const char* nodeID, const char* attributeName, const nsString& newValue);
nsresult UpdateParagraphState(const char* observerName, const char* attributeName, nsString& ioParaFormat);
nsresult UpdateListState(const char* observerName, const char* tagName);
nsresult UpdateTextState(const char* tagName, const char* observerName, const char* attributeName, PRInt8& ioState);
nsresult UpdateFontFace(const char* observerName, const char* attributeName, nsString& ioFontString);
nsresult UpdateDirtyState(PRBool aNowDirty);
// this class should not hold references to the editor or editorShell. Doing
// so would result in cirular reference chains.
nsIHighLevelHTMLEditor* mEditor; // the HTML editor
nsIWebShell* mWebShell; // web shell for the chrome area
// current state
PRInt8 mBoldState;
PRInt8 mItalicState;
PRInt8 mUnderlineState;
PRInt8 mDirtyState;
nsString mParagraphFormat;
nsString mFontString;
nsString mListTag; // contains "" for none, "ol" or "ul"
};
extern "C" nsresult NS_NewInterfaceState(nsIHighLevelHTMLEditor* aEditor, nsIWebShell* aWebShell, nsIDOMSelectionListener** aInstancePtrResult);
#endif // nsInterfaceState_h__

View File

@@ -0,0 +1,86 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsInternetCiter.h"
#include "nsString.h"
/** Mail citations using the Internet style >> This is a citation <<
*/
nsInternetCiter::nsInternetCiter()
{
}
nsInternetCiter::~nsInternetCiter()
{
}
NS_IMPL_ADDREF(nsInternetCiter)
NS_IMPL_RELEASE(nsInternetCiter)
NS_IMETHODIMP
nsInternetCiter::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(nsCOMTypeInfo<nsISupports>::GetIID()))
{
*aInstancePtr = (void*)this;
NS_ADDREF_THIS();
return NS_OK;
}
if (aIID.Equals(nsICiter::GetIID())) {
*aInstancePtr = (void*)(nsICiter*)this;
NS_ADDREF_THIS();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMETHODIMP
nsInternetCiter::GetCiteString(const nsString& aInString, nsString& aOutString)
{
PRUnichar newline ('\n');
PRInt32 i = 0;
PRInt32 length = aInString.Length();
aOutString = "\n\n";
PRUnichar uch = newline;
// Loop over the string:
while (i < length)
{
if (uch == newline)
aOutString += "> ";
uch = aInString[i++];
aOutString += uch;
}
if (uch != newline)
aOutString += newline;
return NS_OK;
}

View File

@@ -0,0 +1,41 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsInternetCiter_h__
#define nsInternetCiter_h__
#include "nsICiter.h"
#include "nsString.h"
/** Mail citations using the AOL style >> This is a citation <<
*/
class nsInternetCiter : public nsICiter
{
public:
nsInternetCiter();
virtual ~nsInternetCiter();
//Interfaces for addref and release and queryinterface
//NOTE: Use NS_DECL_ISUPPORTS_INHERITED in any class inherited from nsEditor
NS_DECL_ISUPPORTS
NS_IMETHOD GetCiteString(const nsString& aInString, nsString& aOutString);
};
#endif //nsInternetCiter_h__

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,189 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsJSEditorLog_h__
#define nsJSEditorLog_h__
#include "nsIHTMLEditor.h"
#include "nsIFileSpec.h"
#include "nsCOMPtr.h"
/** implementation of a transaction listener object.
*
*/
class nsJSEditorLog : public nsIHTMLEditor
{
private:
nsCOMPtr<nsIFileSpec> mFileSpec;
nsIEditor *mEditor;
PRInt32 mLocked;
PRInt32 mDepth;
public:
/** The default constructor.
*/
nsJSEditorLog(nsIEditor *aEditor, nsIFileSpec *aLogFile);
/** The default destructor.
*/
virtual ~nsJSEditorLog();
/* Macro for AddRef(), Release(), and QueryInterface() */
NS_DECL_ISUPPORTS
/* nsIHTMLEditor method implementations. */
NS_IMETHOD Init(nsIDOMDocument *aDoc,
nsIPresShell *aPresShell);
NS_IMETHOD SetTextProperty(nsIAtom *aProperty,
const nsString *aAttribute,
const nsString *aValue);
NS_IMETHOD GetTextProperty(nsIAtom *aProperty,
const nsString *aAttribute,
const nsString *aValue,
PRBool &aFirst, PRBool &aAll, PRBool &aAny);
NS_IMETHOD GetParagraphFormat(nsString& aParagraphFormat);
NS_IMETHOD SetParagraphFormat(const nsString& aParagraphFormat);
NS_IMETHOD RemoveTextProperty(nsIAtom *aProperty, const nsString *aAttribute);
NS_IMETHOD DeleteSelection(nsIEditor::ESelectionCollapseDirection aAction);
NS_IMETHOD InsertText(const nsString& aStringToInsert);
NS_IMETHOD InsertBreak();
NS_IMETHOD EnableUndo(PRBool aEnable);
NS_IMETHOD Undo(PRUint32 aCount);
NS_IMETHOD CanUndo(PRBool &aIsEnabled, PRBool &aCanUndo);
NS_IMETHOD Redo(PRUint32 aCount);
NS_IMETHOD CanRedo(PRBool &aIsEnabled, PRBool &aCanRedo);
NS_IMETHOD BeginTransaction();
NS_IMETHOD EndTransaction();
NS_IMETHOD MoveSelectionUp(nsIAtom *aIncrement, PRBool aExtendSelection);
NS_IMETHOD MoveSelectionDown(nsIAtom *aIncrement, PRBool aExtendSelection);
NS_IMETHOD MoveSelectionNext(nsIAtom *aIncrement, PRBool aExtendSelection);
NS_IMETHOD MoveSelectionPrevious(nsIAtom *aIncrement, PRBool aExtendSelection);
NS_IMETHOD SelectNext(nsIAtom *aIncrement, PRBool aExtendSelection);
NS_IMETHOD SelectPrevious(nsIAtom *aIncrement, PRBool aExtendSelection);
NS_IMETHOD SelectAll();
NS_IMETHOD BeginningOfDocument();
NS_IMETHOD EndOfDocument();
NS_IMETHOD ScrollUp(nsIAtom *aIncrement);
NS_IMETHOD ScrollDown(nsIAtom *aIncrement);
NS_IMETHOD ScrollIntoView(PRBool aScrollToBegin);
NS_IMETHOD Save();
NS_IMETHOD SaveAs(PRBool aSavingCopy);
NS_IMETHOD Cut();
NS_IMETHOD Copy();
NS_IMETHOD Paste();
NS_IMETHOD PasteAsQuotation();
NS_IMETHOD PasteAsCitedQuotation(const nsString& aCitation);
NS_IMETHOD InsertAsQuotation(const nsString& aQuotedText);
NS_IMETHOD InsertAsCitedQuotation(const nsString& aQuotedText, const nsString& aCitation);
NS_IMETHOD InsertHTML(const nsString &aInputString);
NS_IMETHOD OutputToString(nsString& aOutputString,
const nsString& aFormatType,
PRUint32 aFlags);
NS_IMETHOD OutputToStream(nsIOutputStream* aOutputStream,
const nsString& aFormatType,
const nsString* aCharsetOverride,
PRUint32 aFlags);
NS_IMETHOD ApplyStyleSheet(const nsString& aURL);
NS_IMETHOD GetLocalFileURL(nsIDOMWindow* aParent, const nsString& aFilterType, nsString& aReturn);
NS_IMETHOD SetBackgroundColor(const nsString& aColor);
NS_IMETHOD SetBodyAttribute(const nsString& aAttr, const nsString& aValue);
NS_IMETHOD GetParagraphStyle(nsStringArray *aTagList);
NS_IMETHOD AddBlockParent(nsString& aParentTag);
NS_IMETHOD ReplaceBlockParent(nsString& aParentTag);
NS_IMETHOD RemoveParagraphStyle();
NS_IMETHOD RemoveParent(const nsString &aParentTag);
NS_IMETHOD InsertList(const nsString& aListType);
NS_IMETHOD Indent(const nsString& aIndent);
NS_IMETHOD Align(const nsString& aAlign);
NS_IMETHOD GetElementOrParentByTagName(const nsString& aTagName, nsIDOMNode *aNode, nsIDOMElement** aReturn);
NS_IMETHOD GetSelectedElement(const nsString& aTagName, nsIDOMElement** aReturn);
NS_IMETHOD CreateElementWithDefaults(const nsString& aTagName, nsIDOMElement** aReturn);
NS_IMETHOD InsertElement(nsIDOMElement* aElement, PRBool aDeleteSelection);
NS_IMETHOD SaveHLineSettings(nsIDOMElement* aElement);
NS_IMETHOD InsertLinkAroundSelection(nsIDOMElement* aAnchorElement);
NS_IMETHOD SelectElement(nsIDOMElement* aElement);
NS_IMETHOD SetCaretAfterElement(nsIDOMElement* aElement);
NS_IMETHOD GetEmbeddedObjects(nsISupportsArray** aNodeList);
NS_IMETHOD GetCellIndexes(nsIDOMElement *aCell, PRInt32 &aColIndex, PRInt32 &aRowIndex);
NS_IMETHOD GetTableSize(nsIDOMElement *aTable, PRInt32 &aRowCount, PRInt32 &aColCount);
NS_IMETHOD GetCellAt(nsIDOMElement* aTable, PRInt32 aRowIndex, PRInt32 aColIndex, nsIDOMElement* &aCell);
NS_IMETHOD GetCellDataAt(nsIDOMElement* aTable, PRInt32 aRowIndex, PRInt32 aColIndex, nsIDOMElement* &aCell,
PRInt32& aStartRowIndex, PRInt32& aStartColIndex, PRInt32& aRowSpan, PRInt32& aColSpan, PRBool& aIsSelected);
NS_IMETHOD InsertTable();
NS_IMETHOD InsertTableCell(PRInt32 aNumber, PRBool aAfter);
NS_IMETHOD InsertTableColumn(PRInt32 aNumber, PRBool aAfter);
NS_IMETHOD InsertTableRow(PRInt32 aNumber, PRBool aAfter);
NS_IMETHOD DeleteTable();
NS_IMETHOD DeleteTableCell(PRInt32 aNumber);
NS_IMETHOD DeleteTableColumn(PRInt32 aNumber);
NS_IMETHOD DeleteTableRow(PRInt32 aNumber);
NS_IMETHOD JoinTableCells();
NS_IMETHOD NormalizeTable(nsIDOMElement *aTable);
NS_IMETHOD BeginComposition(void);
NS_IMETHOD SetCompositionString(const nsString& aCompositionString, nsIDOMTextRangeList* aTextRangeList);
NS_IMETHOD EndComposition(void);
NS_IMETHOD StartLogging(nsIFileSpec *aLogFile);
NS_IMETHOD StopLogging();
/* nsJSEditorLog public methods. */
nsresult Write(const char *aBuffer);
nsresult WriteInt(const char *aFormat, PRInt32 aInt);
nsresult Flush();
nsresult PrintUnicode(const nsString &aString);
nsresult PrintSelection();
nsresult PrintNode(nsIDOMNode *aNode, PRInt32 aDepth=0);
nsresult PrintElementNode(nsIDOMNode *aNode, PRInt32 aDepth);
nsresult PrintTextNode(nsIDOMNode *aNode, PRInt32 aDepth);
nsresult PrintAttributeNode(nsIDOMNode *aNode, PRInt32 aDepth=0);
nsresult PrintNodeChildren(nsIDOMNode *aNode, PRInt32 aDepth=0);
nsresult GetNodeTreeOffsets(nsIDOMNode *aNode, PRInt32 **aResult, PRInt32 *aLength);
nsresult Lock();
nsresult Unlock();
};
class nsAutoJSEditorLogLock
{
nsJSEditorLog *mLog;
public:
nsAutoJSEditorLogLock(nsJSEditorLog *aLog)
{
mLog = aLog;
if (mLog)
mLog->Lock();
}
~nsAutoJSEditorLogLock()
{
if (mLog)
mLog->Unlock();
}
};
#endif // nsJSEditorLog_h__

View File

@@ -0,0 +1,406 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include <stdio.h>
#include "nsJSEditorLog.h"
#include "nsJSTxnLog.h"
#define LOCK_LOG(doc)
#define UNLOCK_LOG(doc)
static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID);
nsJSTxnLog::nsJSTxnLog(nsJSEditorLog *aEditorLog)
{
mRefCnt = 0;
mIndentLevel = 0;
mBatchCount = 0;
mEditorLog = aEditorLog;
}
nsJSTxnLog::~nsJSTxnLog()
{
}
#define DEBUG_JS_TXN_LOG_REFCNT 1
#ifdef DEBUG_JS_TXN_LOG_REFCNT
nsrefcnt nsJSTxnLog::AddRef(void)
{
return ++mRefCnt;
}
nsrefcnt nsJSTxnLog::Release(void)
{
NS_PRECONDITION(0 != mRefCnt, "dup release");
if (--mRefCnt == 0) {
NS_DELETEXPCOM(this);
return 0;
}
return mRefCnt;
}
#else
NS_IMPL_ADDREF(nsJSTxnLog)
NS_IMPL_RELEASE(nsJSTxnLog)
#endif
NS_IMETHODIMP
nsJSTxnLog::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(kISupportsIID)) {
*aInstancePtr = (void*)(nsISupports*)this;
NS_ADDREF_THIS();
return NS_OK;
}
if (aIID.Equals(nsITransactionListener::GetIID())) {
*aInstancePtr = (void*)(nsITransactionListener*)this;
NS_ADDREF_THIS();
return NS_OK;
}
*aInstancePtr = 0;
return NS_NOINTERFACE;
}
NS_IMETHODIMP
nsJSTxnLog::WillDo(nsITransactionManager *aTxMgr, nsITransaction *aTransaction)
{
LOCK_LOG(this);
PrintIndent(mIndentLevel++);
Write("WillDo: ");
Write(GetString(aTransaction));
Write("\n");
Flush();
UNLOCK_LOG(this);
return NS_OK;
}
NS_IMETHODIMP
nsJSTxnLog::DidDo(nsITransactionManager *aTxMgr, nsITransaction *aTransaction, nsresult aDoResult)
{
LOCK_LOG(this);
PrintIndent(--mIndentLevel);
Write("DidDo: ");
Write(GetString(aTransaction));
Write("(");
WriteInt("%d", aDoResult);
Write(")\n");
Flush();
UNLOCK_LOG(this);
return NS_OK;
}
NS_IMETHODIMP
nsJSTxnLog::WillUndo(nsITransactionManager *aTxMgr, nsITransaction *aTransaction)
{
LOCK_LOG(this);
PrintIndent(mIndentLevel++);
if (aTransaction)
{
Write("WillUndo: ");
Write(GetString(aTransaction));
Write("\n");
}
else
Write("WillUndoBatch\n");
Flush();
UNLOCK_LOG(this);
return NS_OK;
}
NS_IMETHODIMP
nsJSTxnLog::DidUndo(nsITransactionManager *aTxMgr, nsITransaction *aTransaction, nsresult aUndoResult)
{
LOCK_LOG(this);
PrintIndent(--mIndentLevel);
if (aTransaction)
{
Write("DidUndo: ");
Write(GetString(aTransaction));
Write("(");
WriteInt("%d", aUndoResult);
Write(")\n");
}
else
{
Write("EndUndoBatch (");
WriteInt("%d", aUndoResult);
Write(")\n");
}
Flush();
UNLOCK_LOG(this);
return NS_OK;
}
NS_IMETHODIMP
nsJSTxnLog::WillRedo(nsITransactionManager *aTxMgr, nsITransaction *aTransaction)
{
LOCK_LOG(this);
PrintIndent(mIndentLevel++);
if (aTransaction)
{
Write("WillRedo: ");
Write(GetString(aTransaction));
Write("\n");
}
else
Write("WillRedoBatch\n");
Flush();
UNLOCK_LOG(this);
return NS_OK;
}
NS_IMETHODIMP
nsJSTxnLog::DidRedo(nsITransactionManager *aTxMgr, nsITransaction *aTransaction, nsresult aRedoResult)
{
LOCK_LOG(this);
PrintIndent(--mIndentLevel);
if (aTransaction)
{
Write("DidRedo: ");
Write(GetString(aTransaction));
Write(" (");
WriteInt("%d", aRedoResult);
Write(")\n");
}
else
{
Write("DidRedoBatch (");
WriteInt("%d", aRedoResult);
Write(")\n");
}
Flush();
UNLOCK_LOG(this);
return NS_OK;
}
NS_IMETHODIMP
nsJSTxnLog::WillBeginBatch(nsITransactionManager *aTxMgr)
{
LOCK_LOG(this);
PrintIndent(mIndentLevel);
Write("WillBeginBatch: ");
WriteInt("%d", mBatchCount);
Write("\n");
Flush();
UNLOCK_LOG(this);
return NS_OK;
}
NS_IMETHODIMP
nsJSTxnLog::DidBeginBatch(nsITransactionManager *aTxMgr, nsresult aResult)
{
LOCK_LOG(this);
PrintIndent(mIndentLevel++);
Write("DidBeginBatch: ");
WriteInt("%d", mBatchCount++);
Write(" (");
WriteInt("%d", aResult);
Write(")\n");
Flush();
UNLOCK_LOG(this);
return NS_OK;
}
NS_IMETHODIMP
nsJSTxnLog::WillEndBatch(nsITransactionManager *aTxMgr)
{
LOCK_LOG(this);
PrintIndent(--mIndentLevel);
Write("WillEndBatch: ");
WriteInt("%d", --mBatchCount);
Write("\n");
Flush();
UNLOCK_LOG(this);
return NS_OK;
}
NS_IMETHODIMP
nsJSTxnLog::DidEndBatch(nsITransactionManager *aTxMgr, nsresult aResult)
{
LOCK_LOG(this);
PrintIndent(mIndentLevel);
Write("DidEndBatch: ");
WriteInt("%d", mBatchCount);
Write(" (");
WriteInt("%d", aResult);
Write(")\n");
Flush();
UNLOCK_LOG(this);
return NS_OK;
}
NS_IMETHODIMP
nsJSTxnLog::WillMerge(nsITransactionManager *aTxMgr, nsITransaction *aTopTransaction, nsITransaction *aTransaction)
{
LOCK_LOG(this);
PrintIndent(mIndentLevel);
Write("WillMerge: ");
Write(GetString(aTopTransaction));
Write(" <-- ");
Write(GetString(aTransaction));
Write("\n");
Flush();
UNLOCK_LOG(this);
return NS_OK;
}
NS_IMETHODIMP
nsJSTxnLog::DidMerge(nsITransactionManager *aTxMgr, nsITransaction *aTopTransaction, nsITransaction *aTransaction, PRBool aDidMerge, nsresult aMergeResult)
{
LOCK_LOG(this);
PrintIndent(mIndentLevel);
Write("DidMerge: ");
Write(GetString(aTopTransaction));
Write(" <-- ");
Write(GetString(aTransaction));
Write(" (");
Write(aDidMerge ? "TRUE" : "FALSE");
Write(", ");
WriteInt("%d", aMergeResult);
Write(")\n");
Flush();
UNLOCK_LOG(this);
return NS_OK;
}
const char *
nsJSTxnLog::GetString(nsITransaction *aTransaction)
{
static char buf[256];
nsString str = "";
aTransaction->GetRedoString(&str);
if (str.Length() == 0)
str = "<NULL>";
buf[0] = '\0';
str.ToCString(buf, 256);
return buf;
}
nsresult
nsJSTxnLog::PrintIndent(PRInt32 aIndentLevel)
{
PRInt32 i;
Write(" // ");
for (i = 0; i < aIndentLevel; i++)
Write(" ");
return NS_OK;
}
nsresult
nsJSTxnLog::Write(const char *aBuffer)
{
if (!aBuffer)
return NS_ERROR_NULL_POINTER;
if (mEditorLog)
mEditorLog->Write(aBuffer);
else
printf(aBuffer);
return NS_OK;
}
nsresult
nsJSTxnLog::WriteInt(const char *aFormat, PRInt32 aInt)
{
if (!aFormat)
return NS_ERROR_NULL_POINTER;
if (mEditorLog)
mEditorLog->WriteInt(aFormat, aInt);
else
printf(aFormat, aInt);
return NS_OK;
}
nsresult
nsJSTxnLog::Flush()
{
nsresult result = NS_OK;
#ifdef SLOWS_THINGS_WAY_DOWN
if (mEditorLog)
result = mEditorLog->Flush();
else
fflush(stdout);
#endif // SLOWS_THINGS_WAY_DOWN
return result;
}

View File

@@ -0,0 +1,77 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsJSTxnLog_h__
#define nsJSTxnLog_h__
#include "nsITransaction.h"
#include "nsITransactionManager.h"
#include "nsITransactionListener.h"
class nsJSEditorLog;
/** implementation of a transaction listener object.
*
*/
class nsJSTxnLog : public nsITransactionListener
{
private:
nsJSEditorLog *mEditorLog;
PRInt32 mIndentLevel;
PRInt32 mBatchCount;
public:
/** The default constructor.
*/
nsJSTxnLog(nsJSEditorLog *aEditorLog=0);
/** The default destructor.
*/
virtual ~nsJSTxnLog();
/* Macro for AddRef(), Release(), and QueryInterface() */
NS_DECL_ISUPPORTS
/* nsITransactionListener method implementations. */
NS_IMETHOD WillDo(nsITransactionManager *aTxMgr, nsITransaction *aTransaction);
NS_IMETHOD DidDo(nsITransactionManager *aTxMgr, nsITransaction *aTransaction, nsresult aDoResult);
NS_IMETHOD WillUndo(nsITransactionManager *aTxMgr, nsITransaction *aTransaction);
NS_IMETHOD DidUndo(nsITransactionManager *aTxMgr, nsITransaction *aTransaction, nsresult aUndoResult);
NS_IMETHOD WillRedo(nsITransactionManager *aTxMgr, nsITransaction *aTransaction);
NS_IMETHOD DidRedo(nsITransactionManager *aTxMgr, nsITransaction *aTransaction, nsresult aRedoResult);
NS_IMETHOD WillBeginBatch(nsITransactionManager *aTxMgr);
NS_IMETHOD DidBeginBatch(nsITransactionManager *aTxMgr, nsresult aResult);
NS_IMETHOD WillEndBatch(nsITransactionManager *aTxMgr);
NS_IMETHOD DidEndBatch(nsITransactionManager *aTxMgr, nsresult aResult);
NS_IMETHOD WillMerge(nsITransactionManager *aTxMgr, nsITransaction *aTopTransaction, nsITransaction *aTransaction);
NS_IMETHOD DidMerge(nsITransactionManager *aTxMgr, nsITransaction *aTopTransaction, nsITransaction *aTransaction, PRBool aDidMerge, nsresult aMergeResult);
private:
/* nsJSTxnLog private methods. */
const char *GetString(nsITransaction *aTransaction);
nsresult PrintIndent(PRInt32 aIndentLevel);
nsresult Write(const char *aBuffer);
nsresult WriteInt(const char *aFormat, PRInt32 aInt);
nsresult Flush();
};
#endif // nsJSTxnLog_h__

View File

@@ -0,0 +1,297 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsEditor.h"
#include "nsIPresShell.h"
#include "nsICSSStyleSheet.h"
#include "nsIStyleSet.h"
#include "nsIDocument.h"
#include "nsIDocumentObserver.h"
#include "nsStyleSheetTxns.h"
AddStyleSheetTxn::AddStyleSheetTxn()
: mEditor(NULL)
{
}
AddStyleSheetTxn::~AddStyleSheetTxn()
{
}
NS_IMETHODIMP
AddStyleSheetTxn::Init(nsIEditor *aEditor, nsICSSStyleSheet *aSheet)
{
if (!aEditor)
return NS_ERROR_INVALID_ARG;
if (!aSheet)
return NS_ERROR_INVALID_ARG;
mEditor = aEditor;
mSheet = do_QueryInterface(aSheet);
return NS_OK;
}
NS_IMETHODIMP
AddStyleSheetTxn::Do()
{
if (!mEditor || !mSheet)
return NS_ERROR_NOT_INITIALIZED;
nsCOMPtr<nsIPresShell> presShell;
mEditor->GetPresShell(getter_AddRefs(presShell));
if (!presShell)
return NS_ERROR_UNEXPECTED;
nsCOMPtr<nsIStyleSet> styleSet;
nsresult rv = presShell->GetStyleSet(getter_AddRefs(styleSet));
if (NS_SUCCEEDED(rv) && styleSet)
{
nsCOMPtr<nsIStyleSheet> styleSheet = do_QueryInterface(mSheet);
if (styleSheet)
{
nsCOMPtr<nsIDocument> document;
rv = presShell->GetDocument(getter_AddRefs(document));
if (NS_SUCCEEDED(rv) && document)
document->AddStyleSheet(styleSheet);
}
}
return rv;
}
NS_IMETHODIMP
AddStyleSheetTxn::Undo()
{
if (!mEditor || !mSheet)
return NS_ERROR_NOT_INITIALIZED;
nsCOMPtr<nsIPresShell> presShell;
mEditor->GetPresShell(getter_AddRefs(presShell));
if (!presShell)
return NS_ERROR_UNEXPECTED;
nsCOMPtr<nsIStyleSet> styleSet;
nsresult rv = presShell->GetStyleSet(getter_AddRefs(styleSet));
if (NS_SUCCEEDED(rv) && styleSet)
{
styleSet->RemoveDocStyleSheet(mSheet);
nsCOMPtr<nsIDocumentObserver> observer = do_QueryInterface(presShell);
nsCOMPtr<nsIStyleSheet> styleSheet = do_QueryInterface(mSheet);
nsCOMPtr<nsIDocument> document;
rv = presShell->GetDocument(getter_AddRefs(document));
if (NS_SUCCEEDED(rv) && document && observer && styleSheet)
rv = observer->StyleSheetRemoved(document, styleSheet);
}
return rv;
}
NS_IMETHODIMP
AddStyleSheetTxn::Redo()
{
return Do();
}
NS_IMETHODIMP
AddStyleSheetTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
// set out param default value
if (!aDidMerge)
return NS_ERROR_NULL_POINTER;
*aDidMerge = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP
AddStyleSheetTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP
AddStyleSheetTxn::GetUndoString(nsString *aString)
{
if (aString)
{
*aString="Remove Style Sheet";
}
return NS_OK;
}
NS_IMETHODIMP
AddStyleSheetTxn::GetRedoString(nsString *aString)
{
if (aString)
{
*aString="Add Style Sheet";
}
return NS_OK;
}
#ifdef XP_MAC
#pragma mark -
#endif
RemoveStyleSheetTxn::RemoveStyleSheetTxn()
: mEditor(NULL)
{
}
RemoveStyleSheetTxn::~RemoveStyleSheetTxn()
{
}
NS_IMETHODIMP
RemoveStyleSheetTxn::Init(nsIEditor *aEditor, nsICSSStyleSheet *aSheet)
{
if (!aEditor)
return NS_ERROR_INVALID_ARG;
if (!aSheet)
return NS_ERROR_INVALID_ARG;
mEditor = aEditor;
mSheet = do_QueryInterface(aSheet);
return NS_OK;
}
NS_IMETHODIMP
RemoveStyleSheetTxn::Do()
{
if (!mEditor || !mSheet)
return NS_ERROR_NOT_INITIALIZED;
nsCOMPtr<nsIPresShell> presShell;
mEditor->GetPresShell(getter_AddRefs(presShell));
if (!presShell)
return NS_ERROR_UNEXPECTED;
nsCOMPtr<nsIStyleSet> styleSet;
nsresult rv = presShell->GetStyleSet(getter_AddRefs(styleSet));
if (NS_SUCCEEDED(rv) && styleSet)
{
styleSet->RemoveDocStyleSheet(mSheet);
nsCOMPtr<nsIDocumentObserver> observer = do_QueryInterface(presShell);
nsCOMPtr<nsIStyleSheet> styleSheet = do_QueryInterface(mSheet);
nsCOMPtr<nsIDocument> document;
rv = presShell->GetDocument(getter_AddRefs(document));
if (NS_SUCCEEDED(rv) && document && observer && styleSheet)
rv = observer->StyleSheetRemoved(document, styleSheet);
}
return rv;
}
NS_IMETHODIMP
RemoveStyleSheetTxn::Undo()
{
if (!mEditor || !mSheet)
return NS_ERROR_NOT_INITIALIZED;
nsCOMPtr<nsIPresShell> presShell;
mEditor->GetPresShell(getter_AddRefs(presShell));
if (!presShell)
return NS_ERROR_UNEXPECTED;
nsCOMPtr<nsIStyleSet> styleSet;
nsresult rv = presShell->GetStyleSet(getter_AddRefs(styleSet));
if (NS_SUCCEEDED(rv) && styleSet)
{
nsCOMPtr<nsIStyleSheet> styleSheet = do_QueryInterface(mSheet);
if (styleSheet)
{
nsCOMPtr<nsIDocument> document;
rv = presShell->GetDocument(getter_AddRefs(document));
if (NS_SUCCEEDED(rv) && document)
document->AddStyleSheet(styleSheet);
}
}
return rv;
}
NS_IMETHODIMP
RemoveStyleSheetTxn::Redo()
{
return Do();
}
NS_IMETHODIMP
RemoveStyleSheetTxn::Merge(PRBool *aDidMerge, nsITransaction *aTransaction)
{
// set out param default value
if (!aDidMerge)
return NS_ERROR_NULL_POINTER;
*aDidMerge = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP
RemoveStyleSheetTxn::Write(nsIOutputStream *aOutputStream)
{
return NS_OK;
}
NS_IMETHODIMP
RemoveStyleSheetTxn::GetUndoString(nsString *aString)
{
if (aString)
{
*aString="Add Style Sheet";
}
return NS_OK;
}
NS_IMETHODIMP
RemoveStyleSheetTxn::GetRedoString(nsString *aString)
{
if (aString)
{
*aString="Remove Style Sheet";
}
return NS_OK;
}

View File

@@ -0,0 +1,124 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsStylesheetTxns_h__
#define nsStylesheetTxns_h__
#include "EditTxn.h"
#include "nsCOMPtr.h"
#include "nsIEditor.h"
#include "nsICSSStyleSheet.h"
#define ADD_STYLESHEET_TXN_CID \
{/* d05e2980-2fbe-11d3-9ce4-e8393835307c */ \
0xd05e2980, 0x2fbe, 0x11d3, { 0x9c, 0xe4, 0xe8, 0x39, 0x38, 0x35, 0x30, 0x7c } }
#define REMOVE_STYLESHEET_TXN_CID \
{/* d05e2981-2fbe-11d3-9ce4-e8393835307c */ \
0xd05e2981, 0x2fbe, 0x11d3, { 0x9c, 0xe4, 0xe8, 0x39, 0x38, 0x35, 0x30, 0x7c } }
class AddStyleSheetTxn : public EditTxn
{
friend class TransactionFactory;
public:
static const nsIID& GetCID() { static nsIID iid = ADD_STYLESHEET_TXN_CID; return iid; }
virtual ~AddStyleSheetTxn();
/** Initialize the transaction.
* @param aEditor the object providing core editing operations
* @param aSheet the stylesheet to add
*/
NS_IMETHOD Init(nsIEditor *aEditor,
nsICSSStyleSheet *aSheet);
private:
AddStyleSheetTxn();
public:
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Redo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
protected:
nsIEditor* mEditor; // the editor that created this transaction
nsCOMPtr<nsICSSStyleSheet> mSheet; // the style sheet to add
};
class RemoveStyleSheetTxn : public EditTxn
{
friend class TransactionFactory;
public:
static const nsIID& GetCID() { static nsIID iid = REMOVE_STYLESHEET_TXN_CID; return iid; }
virtual ~RemoveStyleSheetTxn();
/** Initialize the transaction.
* @param aEditor the object providing core editing operations
* @param aSheet the stylesheet to remove
*/
NS_IMETHOD Init(nsIEditor *aEditor,
nsICSSStyleSheet *aSheet);
private:
RemoveStyleSheetTxn();
public:
NS_IMETHOD Do(void);
NS_IMETHOD Undo(void);
NS_IMETHOD Redo(void);
NS_IMETHOD Merge(PRBool *aDidMerge, nsITransaction *aTransaction);
NS_IMETHOD Write(nsIOutputStream *aOutputStream);
NS_IMETHOD GetUndoString(nsString *aString);
NS_IMETHOD GetRedoString(nsString *aString);
protected:
nsIEditor* mEditor; // the editor that created this transaction
nsCOMPtr<nsICSSStyleSheet> mSheet; // the style sheet to remove
};
#endif /* nsStylesheetTxns_h__ */

View File

@@ -0,0 +1,124 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsTextEditFactory.h"
#include "nsITextEditor.h"
#include "nsTextEditor.h"
#include "nsEditor.h"
#include "nsEditorCID.h"
#include "nsIComponentManager.h"
static NS_DEFINE_CID(kTextEditorCID, NS_TEXTEDITOR_CID);
nsresult
GetTextEditFactory(nsIFactory **aFactory, const nsCID & aClass)
{
PR_EnterMonitor(GetEditorMonitor());
nsTextEditFactory *factory = new nsTextEditFactory(aClass);
if (!factory)
return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsIFactory> pNSIFactory = do_QueryInterface(factory);
if (!pNSIFactory)
return NS_ERROR_NO_INTERFACE;
nsresult result = pNSIFactory->QueryInterface(nsIFactory::GetIID(),
(void **)aFactory);
PR_ExitMonitor(GetEditorMonitor());
return result;
}
////////////////////////////////////////////////////////////////////////////
// from nsISupports
nsresult
nsTextEditFactory::QueryInterface(const nsIID& aIID, void** aInstancePtr)
{
if (nsnull == aInstancePtr) {
NS_NOTREACHED("!nsEditor");
return NS_ERROR_NULL_POINTER;
}
if (aIID.Equals(nsIFactory::GetIID()) ||
aIID.Equals(nsCOMTypeInfo<nsISupports>::GetIID())) {
*aInstancePtr = (void*) this;
AddRef();
return NS_OK;
}
return NS_NOINTERFACE;
}
NS_IMPL_ADDREF(nsTextEditFactory)
NS_IMPL_RELEASE(nsTextEditFactory)
////////////////////////////////////////////////////////////////////////////
// from nsIFactory:
NS_IMETHODIMP
nsTextEditFactory::CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
*aResult = nsnull;
nsISupports *obj = nsnull;
if (!aResult)
return NS_ERROR_NULL_POINTER;
if (aOuter && !aIID.Equals(nsCOMTypeInfo<nsISupports>::GetIID()))
return NS_NOINTERFACE; // XXX right error?
if (mCID.Equals(kTextEditorCID))
{
//Need to cast to interface first to avoid "ambiguous conversion..." error
// because of multiple nsISupports in the class hierarchy
obj = (nsISupports *)(nsITextEditor*)new nsTextEditor();
}
//more class ids to support. here
if (obj && NS_FAILED(obj->QueryInterface(aIID, (void**)aResult)) )
{
delete obj;
return NS_NOINTERFACE;
}
return NS_OK;
}
NS_IMETHODIMP
nsTextEditFactory::LockFactory(PRBool aLock)
{
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////
// from nsTextEditFactory:
nsTextEditFactory::nsTextEditFactory(const nsCID &aClass)
:mCID(aClass)
{
NS_INIT_REFCNT();
}
nsTextEditFactory::~nsTextEditFactory()
{
//nsComponentManager::UnregisterFactory(mCID, (nsIFactory *)this); //we are out of ref counts anyway
}

View File

@@ -0,0 +1,66 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://wwwt.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsTextEditFactory_h___
#define nsTextEditFactory_h___
#include "nsISupports.h"
#include "nsIFactory.h"
/*
Factory that can make a text editor
*/
/**
* This supplies the neccessary entrance to the edit module. it will return any
* instantiations that we need.
*/
class nsTextEditFactory;
extern nsresult GetTextEditFactory(nsIFactory **aFactory, const nsCID & aClass);
class nsTextEditFactory : public nsIFactory {
public:
////////////////////////////////////////////////////////////////////////////
// from nsISupports and AggregatedQueryInterface:
NS_DECL_ISUPPORTS
////////////////////////////////////////////////////////////////////////////
// from nsIFactory:
NS_IMETHOD
CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult);
NS_IMETHOD
LockFactory(PRBool aLock);
////////////////////////////////////////////////////////////////////////////
virtual ~nsTextEditFactory(void);
private:
nsTextEditFactory(const nsCID &aClass); //will fill the aFactory with the result from queryinterface
/** GetTextEditFactory
* creates an edit factory other CSID supported friend functions here.
*/
friend nsresult GetTextEditFactory(nsIFactory **, const nsCID & );
const nsCID &mCID;
};
#endif //nsIEditFactory_h___

View File

@@ -0,0 +1,968 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL") you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsTextEditRules.h"
#include "nsEditor.h"
#include "PlaceholderTxn.h"
#include "InsertTextTxn.h"
#include "nsCOMPtr.h"
#include "nsIDOMNode.h"
#include "nsIDOMElement.h"
#include "nsIDOMNodeList.h"
#include "nsIDOMSelection.h"
#include "nsIDOMRange.h"
#include "nsIDOMCharacterData.h"
#include "nsIContent.h"
#include "nsIContentIterator.h"
#include "nsIEnumerator.h"
#include "nsLayoutCID.h"
#include "nsIEditProperty.h"
static NS_DEFINE_CID(kCContentIteratorCID, NS_CONTENTITERATOR_CID);
#define CANCEL_OPERATION_IF_READONLY_OR_DISABLED \
if ((mFlags & nsIHighLevelHTMLEditor::eEditorReadonlyMask) || (mFlags & nsIHighLevelHTMLEditor::eEditorDisabledMask)) \
{ \
*aCancel = PR_TRUE; \
return NS_OK; \
};
/********************************************************
* Constructor/Destructor
********************************************************/
nsTextEditRules::nsTextEditRules(PRUint32 aFlags)
: mEditor(nsnull)
, mFlags(aFlags)
{
}
nsTextEditRules::~nsTextEditRules()
{
// do NOT delete mEditor here. We do not hold a ref count to mEditor. mEditor owns our lifespan.
}
/********************************************************
* Public methods
********************************************************/
NS_IMETHODIMP
nsTextEditRules::Init(nsHTMLEditor *aEditor)
{
if (!aEditor) { return NS_ERROR_NULL_POINTER; }
mEditor = aEditor; // we hold a non-refcounted reference back to our editor
nsCOMPtr<nsIDOMSelection> selection;
mEditor->GetSelection(getter_AddRefs(selection));
NS_ASSERTION(selection, "editor cannot get selection");
nsresult result = CreateBogusNodeIfNeeded(selection); // this method handles null selection, which should never happen anyway
return result;
}
NS_IMETHODIMP
nsTextEditRules::GetFlags(PRUint32 *aFlags)
{
if (!aFlags) { return NS_ERROR_NULL_POINTER; }
*aFlags = mFlags;
return NS_OK;
}
NS_IMETHODIMP
nsTextEditRules::SetFlags(PRUint32 aFlags)
{
if (mFlags == aFlags) return NS_OK;
// XXX - this won't work if body element already has
// a style attribute on it, don't know why.
// SetFlags() is really meant to only be called once
// and at editor init time.
if (aFlags & nsIHighLevelHTMLEditor::eEditorPlaintextMask)
{
if (!(mFlags & nsIHighLevelHTMLEditor::eEditorPlaintextMask))
{
// we are converting TO a plaintext editor
// put a "white-space: pre" style on the body
nsCOMPtr<nsIDOMElement> bodyElement;
nsresult res = mEditor->GetBodyElement(getter_AddRefs(bodyElement));
if (NS_SUCCEEDED(res) && bodyElement)
{
// not going through the editor to do this.
bodyElement->SetAttribute("style", "white-space: pre");
}
}
}
mFlags = aFlags;
return NS_OK;
}
NS_IMETHODIMP
nsTextEditRules::WillDoAction(nsIDOMSelection *aSelection,
nsRulesInfo *aInfo, PRBool *aCancel)
{
// null selection is legal
if (!aInfo || !aCancel) { return NS_ERROR_NULL_POINTER; }
*aCancel = PR_FALSE;
// my kingdom for dynamic cast
nsTextRulesInfo *info = NS_STATIC_CAST(nsTextRulesInfo*, aInfo);
switch (info->action)
{
case kInsertBreak:
return WillInsertBreak(aSelection, aCancel);
case kInsertText:
return WillInsertText(aSelection,
aCancel,
info->placeTxn,
info->inString,
info->outString,
info->typeInState,
info->maxLength);
case kDeleteSelection:
return WillDeleteSelection(aSelection, info->collapsedAction, aCancel);
case kUndo:
return WillUndo(aSelection, aCancel);
case kRedo:
return WillRedo(aSelection, aCancel);
case kSetTextProperty:
return WillSetTextProperty(aSelection, aCancel);
case kRemoveTextProperty:
return WillRemoveTextProperty(aSelection, aCancel);
case kOutputText:
return WillOutputText(aSelection,
info->outString,
aCancel);
}
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsTextEditRules::DidDoAction(nsIDOMSelection *aSelection,
nsRulesInfo *aInfo, nsresult aResult)
{
if (!aSelection || !aInfo)
return NS_ERROR_NULL_POINTER;
// my kingdom for dynamic cast
nsTextRulesInfo *info = NS_STATIC_CAST(nsTextRulesInfo*, aInfo);
switch (info->action)
{
case kInsertBreak:
return DidInsertBreak(aSelection, aResult);
case kInsertText:
return DidInsertText(aSelection, aResult);
case kDeleteSelection:
return DidDeleteSelection(aSelection, info->collapsedAction, aResult);
case kUndo:
return DidUndo(aSelection, aResult);
case kRedo:
return DidRedo(aSelection, aResult);
case kSetTextProperty:
return DidSetTextProperty(aSelection, aResult);
case kRemoveTextProperty:
return DidRemoveTextProperty(aSelection, aResult);
case kOutputText:
return DidOutputText(aSelection, aResult);
}
return NS_ERROR_FAILURE;
}
/********************************************************
* Protected methods
********************************************************/
nsresult
nsTextEditRules::WillInsert(nsIDOMSelection *aSelection, PRBool *aCancel)
{
if (!aSelection || !aCancel)
return NS_ERROR_NULL_POINTER;
CANCEL_OPERATION_IF_READONLY_OR_DISABLED
// initialize out param
*aCancel = PR_FALSE;
// check for the magic content node and delete it if it exists
if (mBogusNode)
{
mEditor->DeleteNode(mBogusNode);
mBogusNode = do_QueryInterface(nsnull);
// there is no longer any legit selection, so clear it.
aSelection->ClearSelection();
}
return NS_OK;
}
nsresult
nsTextEditRules::DidInsert(nsIDOMSelection *aSelection, nsresult aResult)
{
return NS_OK;
}
nsresult
nsTextEditRules::WillInsertBreak(nsIDOMSelection *aSelection, PRBool *aCancel)
{
if (!aSelection || !aCancel) { return NS_ERROR_NULL_POINTER; }
CANCEL_OPERATION_IF_READONLY_OR_DISABLED
if (mFlags & nsIHighLevelHTMLEditor::eEditorSingleLineMask) {
*aCancel = PR_TRUE;
}
else {
*aCancel = PR_FALSE;
}
return NS_OK;
}
nsresult
nsTextEditRules::DidInsertBreak(nsIDOMSelection *aSelection, nsresult aResult)
{
return NS_OK;
}
nsresult
nsTextEditRules::WillInsertText(nsIDOMSelection *aSelection,
PRBool *aCancel,
PlaceholderTxn **aTxn,
const nsString *aInString,
nsString *aOutString,
TypeInState aTypeInState,
PRInt32 aMaxLength)
{
if (!aSelection || !aCancel || !aInString || !aOutString) {return NS_ERROR_NULL_POINTER;}
CANCEL_OPERATION_IF_READONLY_OR_DISABLED
nsresult result;
nsString inString = *aInString; // we might want to mutate the input
// before setting the output, do that in a local var
if ((-1 != aMaxLength) && (mFlags & nsIHighLevelHTMLEditor::eEditorPlaintextMask))
{
// get the current text length
// get the length of inString
// if len(doc) is at or over max, cancel the insert
// if l(doc) + l(input) > max, set aOutString to subset of inString so length = max
PRInt32 docLength;
result = mEditor->GetDocumentLength(&docLength);
if (NS_SUCCEEDED(result))
{
if (docLength >= aMaxLength)
{
*aOutString = "";
*aCancel = PR_TRUE;
return result;
}
else
{
PRInt32 inCount = inString.Length();
if ((inCount+docLength)>aMaxLength)
{
inString.Truncate(aMaxLength-docLength);
}
}
}
}
// initialize out params
*aCancel = PR_FALSE;
if (mFlags & nsIHighLevelHTMLEditor::eEditorPasswordMask)
{
// manage the password buffer
PRInt32 start, end;
result = mEditor->GetTextSelectionOffsets(aSelection, start, end);
NS_ASSERTION((NS_SUCCEEDED(result)), "getTextSelectionOffsets failed!");
mPasswordText.Insert(inString, start);
char *password = mPasswordText.ToNewCString();
printf("mPasswordText is %s\n", password);
delete [] password;
// change the output to '*' only
PRInt32 length = inString.Length();
PRInt32 i;
for (i=0; i<length; i++)
*aOutString += '*';
}
else
{
*aOutString = inString;
}
if (mBogusNode || (PR_TRUE==aTypeInState.IsAnySet()))
{
result = TransactionFactory::GetNewTransaction(PlaceholderTxn::GetCID(), (EditTxn **)aTxn);
if (NS_FAILED(result)) { return result; }
if (!*aTxn) { return NS_ERROR_NULL_POINTER; }
(*aTxn)->SetName(InsertTextTxn::gInsertTextTxnName);
mEditor->Do(*aTxn);
}
result = WillInsert(aSelection, aCancel);
if (NS_SUCCEEDED(result) && (PR_FALSE==*aCancel))
{
if (PR_TRUE==aTypeInState.IsAnySet())
{ // for every property that is set, insert a new inline style node
result = CreateStyleForInsertText(aSelection, aTypeInState);
}
}
return result;
}
nsresult
nsTextEditRules::DidInsertText(nsIDOMSelection *aSelection,
nsresult aResult)
{
return DidInsert(aSelection, aResult);
}
nsresult
nsTextEditRules::CreateStyleForInsertText(nsIDOMSelection *aSelection, TypeInState &aTypeInState)
{
// private method, we know aSelection is not null, and that it is collapsed
NS_ASSERTION(nsnull!=aSelection, "bad selection");
// We know at least one style is set and we're about to insert at least one character.
// If the selection is in a text node, split the node (even if we're at the beginning or end)
// then put the text node inside new inline style parents.
// Otherwise, create the text node and the new inline style parents.
nsCOMPtr<nsIDOMNode>anchor;
PRInt32 offset;
nsresult result = aSelection->GetAnchorNode( getter_AddRefs(anchor));
if (NS_SUCCEEDED(result) && NS_SUCCEEDED(aSelection->GetAnchorOffset(&offset)) && anchor)
{
nsCOMPtr<nsIDOMCharacterData>anchorAsText;
anchorAsText = do_QueryInterface(anchor);
if (anchorAsText)
{
nsCOMPtr<nsIDOMNode>newTextNode;
// create an empty text node by splitting the selected text node according to offset
if (0==offset)
{
result = mEditor->SplitNode(anchorAsText, offset, getter_AddRefs(newTextNode));
}
else
{
PRUint32 length;
anchorAsText->GetLength(&length);
if (length==(PRUint32)offset)
{
// newTextNode will be the left node
result = mEditor->SplitNode(anchorAsText, offset, getter_AddRefs(newTextNode));
// but we want the right node in this case
newTextNode = do_QueryInterface(anchor);
}
else
{
// splitting anchor twice sets newTextNode as an empty text node between
// two halves of the original text node
result = mEditor->SplitNode(anchorAsText, offset, getter_AddRefs(newTextNode));
result = mEditor->SplitNode(anchorAsText, 0, getter_AddRefs(newTextNode));
}
}
// now we have the new text node we are going to insert into.
// create style nodes or move it up the content hierarchy as needed.
if ((NS_SUCCEEDED(result)) && newTextNode)
{
nsCOMPtr<nsIDOMNode>newStyleNode;
if (aTypeInState.IsSet(NS_TYPEINSTATE_BOLD))
{
if (PR_TRUE==aTypeInState.GetBold()) {
result = InsertStyleNode(newTextNode, nsIEditProperty::b, aSelection, getter_AddRefs(newStyleNode));
}
else {
printf("not yet implemented, make not bold in a bold context\n");
}
}
if (aTypeInState.IsSet(NS_TYPEINSTATE_ITALIC))
{
if (PR_TRUE==aTypeInState.GetItalic()) {
result = InsertStyleNode(newTextNode, nsIEditProperty::i, aSelection, getter_AddRefs(newStyleNode));
}
else
{
printf("not yet implemented, make not italic in a italic context\n");
}
}
if (aTypeInState.IsSet(NS_TYPEINSTATE_UNDERLINE))
{
if (PR_TRUE==aTypeInState.GetUnderline()) {
result = InsertStyleNode(newTextNode, nsIEditProperty::u, aSelection, getter_AddRefs(newStyleNode));
}
else
{
printf("not yet implemented, make not underline in an underline context\n");
}
}
if (aTypeInState.IsSet(NS_TYPEINSTATE_FONTCOLOR))
{
nsAutoString value;
aTypeInState.GetFontColor(value);
nsAutoString attr;
nsIEditProperty::color->ToString(attr);
result = CreateFontStyleForInsertText(newTextNode, attr, value, aSelection);
}
if (aTypeInState.IsSet(NS_TYPEINSTATE_FONTFACE))
{
nsAutoString value;
aTypeInState.GetFontFace(value);
nsAutoString attr;
nsIEditProperty::face->ToString(attr);
result = CreateFontStyleForInsertText(newTextNode, attr, value, aSelection);
}
if (aTypeInState.IsSet(NS_TYPEINSTATE_FONTSIZE))
{
nsAutoString value;
aTypeInState.GetFontSize(value);
nsAutoString attr;
nsIEditProperty::size->ToString(attr);
result = CreateFontStyleForInsertText(newTextNode, attr, value, aSelection);
}
}
}
else
{
printf("not yet implemented. selection is not text.\n");
}
}
else // we have no selection, so insert a style tag in the body
{
nsCOMPtr<nsIDOMDocument>doc;
mEditor->GetDocument(getter_AddRefs(doc));
nsCOMPtr<nsIDOMNodeList>nodeList;
nsAutoString bodyTag = "body";
result = doc->GetElementsByTagName(bodyTag, getter_AddRefs(nodeList));
if ((NS_SUCCEEDED(result)) && nodeList)
{
PRUint32 count;
nodeList->GetLength(&count);
NS_ASSERTION(1==count, "there is not exactly 1 body in the document!");
nsCOMPtr<nsIDOMNode>bodyNode;
result = nodeList->Item(0, getter_AddRefs(bodyNode));
if ((NS_SUCCEEDED(result)) && bodyNode)
{ // now we've got the body tag. insert the style tag
if (aTypeInState.IsSet(NS_TYPEINSTATE_BOLD))
{
if (PR_TRUE==aTypeInState.GetBold()) {
InsertStyleAndNewTextNode(bodyNode, nsIEditProperty::b, aSelection);
}
}
if (aTypeInState.IsSet(NS_TYPEINSTATE_ITALIC))
{
if (PR_TRUE==aTypeInState.GetItalic()) {
InsertStyleAndNewTextNode(bodyNode, nsIEditProperty::i, aSelection);
}
}
if (aTypeInState.IsSet(NS_TYPEINSTATE_UNDERLINE))
{
if (PR_TRUE==aTypeInState.GetUnderline()) {
InsertStyleAndNewTextNode(bodyNode, nsIEditProperty::u, aSelection);
}
}
}
}
}
return result;
}
nsresult
nsTextEditRules::CreateFontStyleForInsertText(nsIDOMNode *aNewTextNode,
const nsString &aAttr,
const nsString &aValue,
nsIDOMSelection *aSelection)
{
nsresult result = NS_OK;
nsCOMPtr<nsIDOMNode>newStyleNode;
if (0!=aValue.Length())
{
result = InsertStyleNode(aNewTextNode, nsIEditProperty::font, aSelection, getter_AddRefs(newStyleNode));
if (NS_SUCCEEDED(result) && newStyleNode)
{
nsCOMPtr<nsIDOMElement>element = do_QueryInterface(newStyleNode);
if (element) {
result = mEditor->SetAttribute(element, aAttr, aValue);
}
}
}
else
{
printf("not yet implemented, undo font in an font context\n");
}
return result;
}
nsresult
nsTextEditRules::InsertStyleNode(nsIDOMNode *aNode,
nsIAtom *aTag,
nsIDOMSelection *aSelection,
nsIDOMNode **aNewNode)
{
NS_ASSERTION(aNode && aTag, "bad args");
if (!aNode || !aTag) { return NS_ERROR_NULL_POINTER; }
nsresult result;
nsCOMPtr<nsIDOMNode>parent;
aNode->GetParentNode(getter_AddRefs(parent));
PRInt32 offsetInParent;
nsEditor::GetChildOffset(aNode, parent, offsetInParent);
nsAutoString tag;
aTag->ToString(tag);
result = mEditor->CreateNode(tag, parent, offsetInParent, aNewNode);
if ((NS_SUCCEEDED(result)) && *aNewNode)
{
result = mEditor->DeleteNode(aNode);
if (NS_SUCCEEDED(result))
{
result = mEditor->InsertNode(aNode, *aNewNode, 0);
if (NS_SUCCEEDED(result)) {
if (aSelection) {
aSelection->Collapse(aNode, 0);
}
}
}
}
return result;
}
nsresult
nsTextEditRules::InsertStyleAndNewTextNode(nsIDOMNode *aParentNode, nsIAtom *aTag, nsIDOMSelection *aSelection)
{
NS_ASSERTION(aParentNode && aTag, "bad args");
if (!aParentNode || !aTag) { return NS_ERROR_NULL_POINTER; }
nsresult result;
// if the selection already points to a text node, just call InsertStyleNode()
if (aSelection)
{
nsCOMPtr<nsIDOMNode>anchor;
PRInt32 offset;
result = aSelection->GetAnchorNode(getter_AddRefs(anchor));
if (NS_SUCCEEDED(result) && NS_SUCCEEDED(aSelection->GetAnchorOffset(&offset)) && anchor)
{
nsCOMPtr<nsIDOMCharacterData>anchorAsText;
anchorAsText = do_QueryInterface(anchor);
if (anchorAsText)
{
nsCOMPtr<nsIDOMNode> newStyleNode;
result = InsertStyleNode(anchor, aTag, aSelection, getter_AddRefs(newStyleNode));
return result;
}
}
}
// if we get here, there is no selected text node so we create one.
nsAutoString tag;
aTag->ToString(tag);
nsCOMPtr<nsIDOMNode>newStyleNode;
nsCOMPtr<nsIDOMNode>newTextNode;
result = mEditor->CreateNode(tag, aParentNode, 0, getter_AddRefs(newStyleNode));
if (NS_SUCCEEDED(result))
{
result = mEditor->CreateNode(nsEditor::GetTextNodeTag(), newStyleNode, 0, getter_AddRefs(newTextNode));
if (NS_SUCCEEDED(result))
{
if (aSelection) {
aSelection->Collapse(newTextNode, 0);
}
}
}
return result;
}
nsresult
nsTextEditRules::WillSetTextProperty(nsIDOMSelection *aSelection, PRBool *aCancel)
{
nsresult result = NS_OK;
// XXX: should probably return a success value other than NS_OK that means "not allowed"
if (nsIHighLevelHTMLEditor::eEditorPlaintextMask & mFlags) {
*aCancel = PR_TRUE;
}
return result;
}
nsresult
nsTextEditRules::DidSetTextProperty(nsIDOMSelection *aSelection, nsresult aResult)
{
return NS_OK;
}
nsresult
nsTextEditRules::WillRemoveTextProperty(nsIDOMSelection *aSelection, PRBool *aCancel)
{
nsresult result = NS_OK;
// XXX: should probably return a success value other than NS_OK that means "not allowed"
if (nsIHighLevelHTMLEditor::eEditorPlaintextMask & mFlags) {
*aCancel = PR_TRUE;
}
return result;
}
nsresult
nsTextEditRules::DidRemoveTextProperty(nsIDOMSelection *aSelection, nsresult aResult)
{
return NS_OK;
}
nsresult
nsTextEditRules::WillDeleteSelection(nsIDOMSelection *aSelection,
nsIEditor::ESelectionCollapseDirection aCollapsedAction,
PRBool *aCancel)
{
if (!aSelection || !aCancel) { return NS_ERROR_NULL_POINTER; }
CANCEL_OPERATION_IF_READONLY_OR_DISABLED
// initialize out param
*aCancel = PR_FALSE;
// if there is only bogus content, cancel the operation
if (mBogusNode) {
*aCancel = PR_TRUE;
return NS_OK;
}
if (mFlags & nsIHighLevelHTMLEditor::eEditorPasswordMask)
{
// manage the password buffer
PRInt32 start, end;
mEditor->GetTextSelectionOffsets(aSelection, start, end);
if (end==start)
{ // collapsed selection
if (nsIEditor::eDeletePrevious==aCollapsedAction && 0<start) { // del back
mPasswordText.Cut(start-1, 1);
}
else if (nsIEditor::eDeleteNext==aCollapsedAction) { // del forward
mPasswordText.Cut(start, 1);
}
// otherwise nothing to do for this collapsed selection
}
else { // extended selection
mPasswordText.Cut(start, end-start);
}
char *password = mPasswordText.ToNewCString();
printf("mPasswordText is %s\n", password);
delete [] password;
}
return NS_OK;
}
// if the document is empty, insert a bogus text node with a &nbsp;
// if we ended up with consecutive text nodes, merge them
nsresult
nsTextEditRules::DidDeleteSelection(nsIDOMSelection *aSelection,
nsIEditor::ESelectionCollapseDirection aCollapsedAction,
nsresult aResult)
{
nsresult result = aResult; // if aResult is an error, we just return it
if (!aSelection) { return NS_ERROR_NULL_POINTER; }
PRBool isCollapsed;
aSelection->GetIsCollapsed(&isCollapsed);
NS_ASSERTION(PR_TRUE==isCollapsed, "selection not collapsed after delete selection.");
// if the delete selection resulted in no content
// insert a special bogus text node with a &nbsp; character in it.
if (NS_SUCCEEDED(result)) // only do this work if DeleteSelection completed successfully
{
result = CreateBogusNodeIfNeeded(aSelection);
// if we don't have an empty document, check the selection to see if any collapsing is necessary
if (!mBogusNode)
{
nsCOMPtr<nsIDOMNode>anchor;
PRInt32 offset;
result = aSelection->GetAnchorNode(getter_AddRefs(anchor));
if (NS_SUCCEEDED(result) && NS_SUCCEEDED(aSelection->GetAnchorOffset(&offset)) && anchor)
{
nsCOMPtr<nsIDOMNodeList> anchorChildren;
result = anchor->GetChildNodes(getter_AddRefs(anchorChildren));
nsCOMPtr<nsIDOMNode> selectedNode;
if ((NS_SUCCEEDED(result)) && anchorChildren) {
result = anchorChildren->Item(offset, getter_AddRefs(selectedNode));
}
else {
selectedNode = do_QueryInterface(anchor);
}
if ((NS_SUCCEEDED(result)) && selectedNode)
{
nsCOMPtr<nsIDOMCharacterData>selectedNodeAsText;
selectedNodeAsText = do_QueryInterface(selectedNode);
if (selectedNodeAsText)
{
nsCOMPtr<nsIDOMNode> siblingNode;
selectedNode->GetPreviousSibling(getter_AddRefs(siblingNode));
if (siblingNode)
{
nsCOMPtr<nsIDOMCharacterData>siblingNodeAsText;
siblingNodeAsText = do_QueryInterface(siblingNode);
if (siblingNodeAsText)
{
PRUint32 siblingLength; // the length of siblingNode before the join
siblingNodeAsText->GetLength(&siblingLength);
nsCOMPtr<nsIDOMNode> parentNode;
selectedNode->GetParentNode(getter_AddRefs(parentNode));
result = mEditor->JoinNodes(siblingNode, selectedNode, parentNode);
// selectedNode will remain after the join, siblingNode is removed
}
}
selectedNode->GetNextSibling(getter_AddRefs(siblingNode));
if (siblingNode)
{
nsCOMPtr<nsIDOMCharacterData>siblingNodeAsText;
siblingNodeAsText = do_QueryInterface(siblingNode);
if (siblingNodeAsText)
{
PRUint32 selectedNodeLength; // the length of siblingNode before the join
selectedNodeAsText->GetLength(&selectedNodeLength);
nsCOMPtr<nsIDOMNode> parentNode;
selectedNode->GetParentNode(getter_AddRefs(parentNode));
result = mEditor->JoinNodes(selectedNode, siblingNode, parentNode);
// selectedNode will remain after the join, siblingNode is removed
// set selection
aSelection->Collapse(siblingNode, selectedNodeLength);
}
}
}
}
}
}
}
return result;
}
nsresult
nsTextEditRules::WillUndo(nsIDOMSelection *aSelection, PRBool *aCancel)
{
if (!aSelection || !aCancel) { return NS_ERROR_NULL_POINTER; }
CANCEL_OPERATION_IF_READONLY_OR_DISABLED
// initialize out param
*aCancel = PR_FALSE;
return NS_OK;
}
/* the idea here is to see if the magic empty node has suddenly reappeared as the result of the undo.
* if it has, set our state so we remember it.
* There is a tradeoff between doing here and at redo, or doing it everywhere else that might care.
* Since undo and redo are relatively rare, it makes sense to take the (small) performance hit here.
*/
nsresult
nsTextEditRules:: DidUndo(nsIDOMSelection *aSelection, nsresult aResult)
{
nsresult result = aResult; // if aResult is an error, we return it.
if (!aSelection) { return NS_ERROR_NULL_POINTER; }
if (NS_SUCCEEDED(result))
{
if (mBogusNode) {
mBogusNode = do_QueryInterface(nsnull);
}
else
{
nsCOMPtr<nsIDOMNode>node;
PRInt32 offset;
result = aSelection->GetAnchorNode(getter_AddRefs(node));
if (NS_SUCCEEDED(result) && NS_SUCCEEDED(aSelection->GetAnchorOffset(&offset)) && node)
{
nsCOMPtr<nsIDOMElement>element;
element = do_QueryInterface(node);
if (element)
{
nsAutoString att(nsEditor::kMOZEditorBogusNodeAttr);
nsAutoString val;
(void)element->GetAttribute(att, val);
if (val.Equals(nsEditor::kMOZEditorBogusNodeValue)) {
mBogusNode = do_QueryInterface(element);
}
}
nsCOMPtr<nsIDOMNode> temp;
result = node->GetParentNode(getter_AddRefs(temp));
node = do_QueryInterface(temp);
}
}
}
return result;
}
nsresult
nsTextEditRules::WillRedo(nsIDOMSelection *aSelection, PRBool *aCancel)
{
if (!aSelection || !aCancel) { return NS_ERROR_NULL_POINTER; }
CANCEL_OPERATION_IF_READONLY_OR_DISABLED
// initialize out param
*aCancel = PR_FALSE;
return NS_OK;
}
nsresult
nsTextEditRules::DidRedo(nsIDOMSelection *aSelection, nsresult aResult)
{
nsresult result = aResult; // if aResult is an error, we return it.
if (!aSelection) { return NS_ERROR_NULL_POINTER; }
if (NS_SUCCEEDED(result))
{
if (mBogusNode) {
mBogusNode = do_QueryInterface(nsnull);
}
else
{
nsCOMPtr<nsIDOMNode>node;
PRInt32 offset;
result = aSelection->GetAnchorNode(getter_AddRefs(node));
if (NS_SUCCEEDED(result) && NS_SUCCEEDED(aSelection->GetAnchorOffset(&offset)) && node)
{
nsCOMPtr<nsIDOMElement>element;
element = do_QueryInterface(node);
if (element)
{
nsAutoString att(nsEditor::kMOZEditorBogusNodeAttr);
nsAutoString val;
(void)element->GetAttribute(att, val);
if (val.Equals(nsEditor::kMOZEditorBogusNodeValue)) {
mBogusNode = do_QueryInterface(element);
}
}
nsCOMPtr<nsIDOMNode> temp;
result = node->GetParentNode(getter_AddRefs(temp));
node = do_QueryInterface(temp);
}
}
}
return result;
}
nsresult
nsTextEditRules::WillOutputText(nsIDOMSelection *aSelection,
nsString *aOutString,
PRBool *aCancel)
{
// null selection ok
if (!aOutString || !aCancel) { return NS_ERROR_NULL_POINTER; }
// initialize out param
*aCancel = PR_FALSE;
if (mFlags & nsIHighLevelHTMLEditor::eEditorPasswordMask)
{
*aOutString = mPasswordText;
*aCancel = PR_TRUE;
}
return NS_OK;
}
nsresult
nsTextEditRules::DidOutputText(nsIDOMSelection *aSelection, nsresult aResult)
{
return NS_OK;
}
nsresult
nsTextEditRules::CreateBogusNodeIfNeeded(nsIDOMSelection *aSelection)
{
if (!aSelection) { return NS_ERROR_NULL_POINTER; }
if (!mEditor) { return NS_ERROR_NULL_POINTER; }
nsCOMPtr<nsIDOMDocument>doc;
mEditor->GetDocument(getter_AddRefs(doc));
nsCOMPtr<nsIDOMNodeList>nodeList;
nsAutoString bodyTag = "body";
nsresult result = doc->GetElementsByTagName(bodyTag, getter_AddRefs(nodeList));
if ((NS_SUCCEEDED(result)) && nodeList)
{
PRUint32 count;
nodeList->GetLength(&count);
NS_ASSERTION(1==count, "there is not exactly 1 body in the document!");
nsCOMPtr<nsIDOMNode>bodyNode;
result = nodeList->Item(0, getter_AddRefs(bodyNode));
if ((NS_SUCCEEDED(result)) && bodyNode)
{ // now we've got the body tag.
// iterate the body tag, looking for editable content
// if no editable content is found, insert the bogus node
PRBool needsBogusContent=PR_TRUE;
nsCOMPtr<nsIDOMNode>bodyChild;
result = bodyNode->GetFirstChild(getter_AddRefs(bodyChild));
while ((NS_SUCCEEDED(result)) && bodyChild)
{
if (PR_TRUE==mEditor->IsEditable(bodyChild))
{
needsBogusContent = PR_FALSE;
break;
}
nsCOMPtr<nsIDOMNode>temp;
bodyChild->GetNextSibling(getter_AddRefs(temp));
bodyChild = do_QueryInterface(temp);
}
if (PR_TRUE==needsBogusContent)
{
// set mBogusNode to be the newly created <P>
result = mEditor->CreateNode(nsAutoString("P"), bodyNode, 0,
getter_AddRefs(mBogusNode));
if ((NS_SUCCEEDED(result)) && mBogusNode)
{
nsCOMPtr<nsIDOMNode>newTNode;
result = mEditor->CreateNode(nsEditor::GetTextNodeTag(), mBogusNode, 0,
getter_AddRefs(newTNode));
if ((NS_SUCCEEDED(result)) && newTNode)
{
nsCOMPtr<nsIDOMCharacterData>newNodeAsText;
newNodeAsText = do_QueryInterface(newTNode);
if (newNodeAsText)
{
nsAutoString data;
data += 160;
newNodeAsText->SetData(data);
aSelection->Collapse(newTNode, 0);
}
}
// make sure we know the PNode is bogus
nsCOMPtr<nsIDOMElement>newPElement;
newPElement = do_QueryInterface(mBogusNode);
if (newPElement)
{
nsAutoString att(nsEditor::kMOZEditorBogusNodeAttr);
nsAutoString val(nsEditor::kMOZEditorBogusNodeValue);
newPElement->SetAttribute(att, val);
}
}
}
}
}
return result;
}

View File

@@ -0,0 +1,201 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsTextEditRules_h__
#define nsTextEditRules_h__
#include "nsCOMPtr.h"
#include "nsHTMLEditor.h"
#include "nsIDOMNode.h"
#include "nsEditRules.h"
#include "TypeInState.h"
class PlaceholderTxn;
class nsTextEditor;
/** Object that encapsulates HTML text-specific editing rules.
*
* To be a good citizen, edit rules must live by these restrictions:
* 1. All data manipulation is through the editor.
* Content nodes in the document tree must <B>not</B> be manipulated directly.
* Content nodes in document fragments that are not part of the document itself
* may be manipulated at will. Operations on document fragments must <B>not</B>
* go through the editor.
* 2. Selection must not be explicitly set by the rule method.
* Any manipulation of Selection must be done by the editor.
*/
class nsTextEditRules : public nsEditRules
{
public:
nsTextEditRules(PRUint32 aFlags);
virtual ~nsTextEditRules();
// nsEditRules methods
NS_IMETHOD Init(nsHTMLEditor *aEditor);
NS_IMETHOD WillDoAction(nsIDOMSelection *aSelection, nsRulesInfo *aInfo, PRBool *aCancel);
NS_IMETHOD DidDoAction(nsIDOMSelection *aSelection, nsRulesInfo *aInfo, nsresult aResult);
NS_IMETHOD GetFlags(PRUint32 *aFlags);
NS_IMETHOD SetFlags(PRUint32 aFlags);
// nsTextEditRules action id's
enum
{
// any editor that has a txn mgr
kUndo = 1000,
kRedo = 1001,
// text actions
kInsertText = 2000,
kDeleteSelection = 2001,
kSetTextProperty = 2003,
kRemoveTextProperty = 2004,
kOutputText = 2005,
// html only action
kInsertBreak = 3000,
kMakeList = 3001,
kIndent = 3002,
kOutdent = 3003,
kAlign = 3004,
kMakeHeader = 3005,
kMakeAddress = 3006,
kMakePRE = 3007
};
protected:
// nsTextEditRules implementation methods
nsresult WillInsertText(nsIDOMSelection *aSelection,
PRBool *aCancel,
PlaceholderTxn **aTxn,
const nsString *inString,
nsString *outString,
TypeInState typeInState,
PRInt32 aMaxLength);
nsresult DidInsertText(nsIDOMSelection *aSelection, nsresult aResult);
nsresult CreateStyleForInsertText(nsIDOMSelection *aSelection, TypeInState &aTypeInState);
nsresult WillInsertBreak(nsIDOMSelection *aSelection, PRBool *aCancel);
nsresult DidInsertBreak(nsIDOMSelection *aSelection, nsresult aResult);
nsresult WillInsert(nsIDOMSelection *aSelection, PRBool *aCancel);
nsresult DidInsert(nsIDOMSelection *aSelection, nsresult aResult);
nsresult WillDeleteSelection(nsIDOMSelection *aSelection,
nsIEditor::ESelectionCollapseDirection aCollapsedAction,
PRBool *aCancel);
nsresult DidDeleteSelection(nsIDOMSelection *aSelection,
nsIEditor::ESelectionCollapseDirection aCollapsedAction,
nsresult aResult);
nsresult WillSetTextProperty(nsIDOMSelection *aSelection, PRBool *aCancel);
nsresult DidSetTextProperty(nsIDOMSelection *aSelection, nsresult aResult);
nsresult WillRemoveTextProperty(nsIDOMSelection *aSelection, PRBool *aCancel);
nsresult DidRemoveTextProperty(nsIDOMSelection *aSelection, nsresult aResult);
nsresult WillUndo(nsIDOMSelection *aSelection, PRBool *aCancel);
nsresult DidUndo(nsIDOMSelection *aSelection, nsresult aResult);
nsresult WillRedo(nsIDOMSelection *aSelection, PRBool *aCancel);
nsresult DidRedo(nsIDOMSelection *aSelection, nsresult aResult);
nsresult WillOutputText(nsIDOMSelection *aSelection, nsString *aOutText, PRBool *aCancel);
nsresult DidOutputText(nsIDOMSelection *aSelection, nsresult aResult);
// helper functions
/** insert aNode into a new style node of type aTag.
* aSelection is optional. If provided, aSelection is set to (aNode, 0)
* if aNode was successfully placed in a new style node
* @param aNewStyleNode [OUT] The newly created style node, if result is successful
* undefined if result is a failure.
*/
nsresult InsertStyleNode(nsIDOMNode *aNode,
nsIAtom *aTag,
nsIDOMSelection *aSelection,
nsIDOMNode **aNewStyleNode);
/** inserts a new <FONT> node and sets the aAttr attribute to aValue */
nsresult CreateFontStyleForInsertText(nsIDOMNode *aNewTextNode,
const nsString &aAttr,
const nsString &aValue,
nsIDOMSelection *aSelection);
/** create a new style node of type aTag in aParentNode, and put a new text node
* in the new style node.
* If aSelection is provided and points to a text node, just call InsertStyleNode instead.
* aSelection is optional. If provided, aSelection is set to (newTextNode, 0)
* if newTextNode was successfully created.
*/
nsresult InsertStyleAndNewTextNode(nsIDOMNode *aParentNode,
nsIAtom *aTag,
nsIDOMSelection *aSelection);
/** creates a bogus text node if the document has no editable content */
nsresult CreateBogusNodeIfNeeded(nsIDOMSelection *aSelection);
/** enforce selection must be inside PRE node */
nsresult PinSelectionInPRE(nsIDOMSelection *aSelection);
// data
nsHTMLEditor *mEditor; // note that we do not refcount the editor
nsString mPasswordText; // a buffer we use to store the real value of password editors
nsCOMPtr<nsIDOMNode> mBogusNode; // magic node acts as placeholder in empty doc
PRUint32 mFlags;
};
class nsTextRulesInfo : public nsRulesInfo
{
public:
nsTextRulesInfo(int aAction) :
nsRulesInfo(aAction),
placeTxn(0),
inString(0),
outString(0),
typeInState(),
maxLength(-1),
collapsedAction(nsIEditor::eDeleteNext)
{};
virtual ~nsTextRulesInfo() {};
// kInsertText
PlaceholderTxn **placeTxn;
const nsString *inString;
nsString *outString;
TypeInState typeInState;
PRInt32 maxLength;
// kDeleteSelection
nsIEditor::ESelectionCollapseDirection collapsedAction;
// kMakeList
PRBool bOrdered;
// kAlign
const nsString *alignType;
};
#endif //nsTextEditRules_h__

View File

@@ -0,0 +1,661 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL") you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#error "This file is no longer used"
#include "nsTextEditor.h"
#include "nsEditorEventListeners.h"
#include "nsIDocument.h"
#include "nsFileSpec.h"
#include "nsIDOMDocument.h"
#include "nsIDOMEventReceiver.h"
#include "nsIDOMKeyListener.h"
#include "nsIDOMMouseListener.h"
#include "nsIDOMDragListener.h"
#include "nsIDOMFocusListener.h"
#include "nsIDOMSelection.h"
#include "nsIDOMNodeList.h"
#include "nsIDOMCharacterData.h"
#include "nsIDOMElement.h"
#include "nsIDOMTextListener.h"
#include "nsIDiskDocument.h"
#include "nsIDocumentEncoder.h"
#include "nsEditorCID.h"
#include "nsISupportsArray.h"
#include "nsIEnumerator.h"
#include "nsIContentIterator.h"
#include "nsIContent.h"
#include "nsLayoutCID.h"
#include "nsIPresShell.h"
#include "nsIStyleContext.h"
#include "nsVoidArray.h"
#if DEBUG
#include "TextEditorTest.h"
#endif
// transactions the text editor knows how to build itself
#include "TransactionFactory.h"
#include "PlaceholderTxn.h"
#include "InsertTextTxn.h"
#include "nsIFileStream.h"
#include "nsIStringStream.h"
#include "nsIAppShell.h"
#include "nsIToolkit.h"
#include "nsWidgetsCID.h"
#include "nsIFileWidget.h"
// Drag & Drop, Clipboard
#include "nsIClipboard.h"
#include "nsITransferable.h"
//#include "nsIFormatConverter.h"
// Drag & Drop, Clipboard Support
static NS_DEFINE_CID(kCClipboardCID, NS_CLIPBOARD_CID);
static NS_DEFINE_CID(kCTransferableCID, NS_TRANSFERABLE_CID);
//static NS_DEFINE_IID(kCXIFFormatConverterCID, NS_XIFFORMATCONVERTER_CID);
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsTextEditRules.h"
#include "nsIPref.h"
#include "nsAOLCiter.h"
#include "nsInternetCiter.h"
#ifdef ENABLE_JS_EDITOR_LOG
#include "nsJSEditorLog.h"
#endif // ENABLE_JS_EDITOR_LOG
static NS_DEFINE_CID(kEditorCID, NS_EDITOR_CID);
static NS_DEFINE_CID(kTextEditorCID, NS_TEXTEDITOR_CID);
static NS_DEFINE_CID(kCContentIteratorCID, NS_CONTENTITERATOR_CID);
static NS_DEFINE_CID(kCRangeCID, NS_RANGE_CID);
static NS_DEFINE_CID(kPrefServiceCID, NS_PREF_CID);
#ifdef NS_DEBUG
static PRBool gNoisy = PR_FALSE;
#else
static const PRBool gNoisy = PR_FALSE;
#endif
/*****************************************************************************
* nsTextEditor implementation
****************************************************************************/
nsTextEditor::nsTextEditor()
: mTypeInState(nsnull)
, mRules(nsnull)
, mKeyListenerP(nsnull)
, mIsComposing(PR_FALSE)
{
// Done in nsEditor
// NS_INIT_REFCNT();
mRules = nsnull;
mMaxTextLength = -1;
mWrapColumn = 72;
}
nsTextEditor::~nsTextEditor()
{}
// Adds appropriate AddRef, Release, and QueryInterface methods for derived class
//NS_IMPL_ISUPPORTS_INHERITED(nsTextEditor, nsEditor, nsITextEditor)
//NS_IMPL_ADDREF_INHERITED(Class, Super)
NS_IMETHODIMP_(nsrefcnt) nsTextEditor::AddRef(void)
{
return nsEditor::AddRef();
}
//NS_IMPL_RELEASE_INHERITED(Class, Super)
NS_IMETHODIMP_(nsrefcnt) nsTextEditor::Release(void)
{
return nsEditor::Release();
}
//NS_IMPL_QUERY_INTERFACE_INHERITED(Class, Super, AdditionalInterface)
NS_IMETHODIMP nsTextEditor::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (!aInstancePtr) return NS_ERROR_NULL_POINTER;
if (aIID.Equals(nsITextEditor::GetIID())) {
*aInstancePtr = NS_STATIC_CAST(nsITextEditor*, this);
NS_ADDREF_THIS();
return NS_OK;
}
return nsEditor::QueryInterface(aIID, aInstancePtr);
}
NS_IMETHODIMP nsTextEditor::Init(nsIDOMDocument *aDoc,
nsIPresShell *aPresShell)
{}
void nsTextEditor::HandleEventListenerError()
{}
void nsTextEditor::InitRules()
{}
NS_IMETHODIMP
nsTextEditor::GetFlags(PRUint32 *aFlags)
{
if (!mRules || !aFlags) { return NS_ERROR_NULL_POINTER; }
return mRules->GetFlags(aFlags);
}
NS_IMETHODIMP
nsTextEditor::SetFlags(PRUint32 aFlags)
{
if (!mRules) { return NS_ERROR_NULL_POINTER; }
return mRules->SetFlags(aFlags);
}
NS_IMETHODIMP nsTextEditor::SetTextProperty(nsIAtom *aProperty,
const nsString *aAttribute,
const nsString *aValue)
{}
NS_IMETHODIMP nsTextEditor::GetTextProperty(nsIAtom *aProperty,
const nsString *aAttribute,
const nsString *aValue,
PRBool &aFirst, PRBool &aAny, PRBool &aAll)
{}
void nsTextEditor::IsTextStyleSet(nsIStyleContext *aSC,
nsIAtom *aProperty,
const nsString *aAttribute,
PRBool &aIsSet) const
{}
// this will NOT find aAttribute unless aAttribute has a non-null value
// so singleton attributes like <Table border> will not be matched!
void nsTextEditor::IsTextPropertySetByContent(nsIDOMNode *aNode,
nsIAtom *aProperty,
const nsString *aAttribute,
const nsString *aValue,
PRBool &aIsSet,
nsIDOMNode **aStyleNode) const
{}
NS_IMETHODIMP nsTextEditor::RemoveTextProperty(nsIAtom *aProperty, const nsString *aAttribute)
{}
void nsTextEditor::GetTextSelectionOffsetsForRange(nsIDOMSelection *aSelection,
nsIDOMNode **aParent,
PRInt32 &aStartOffset,
PRInt32 &aEndOffset)
{}
void nsTextEditor::ResetTextSelectionForRange(nsIDOMNode *aParent,
PRInt32 aStartOffset,
PRInt32 aEndOffset,
nsIDOMSelection *aSelection)
{}
NS_IMETHODIMP nsTextEditor::DeleteSelection(nsIEditor::ESelectionCollapseDirection aAction)
{}
NS_IMETHODIMP nsTextEditor::InsertText(const nsString& aStringToInsert)
{}
NS_IMETHODIMP nsTextEditor::SetMaxTextLength(PRInt32 aMaxTextLength)
{
mMaxTextLength = aMaxTextLength;
return NS_OK;
}
NS_IMETHODIMP nsTextEditor::GetMaxTextLength(PRInt32& aMaxTextLength)
{
aMaxTextLength = mMaxTextLength;
return NS_OK;
}
NS_IMETHODIMP nsTextEditor::InsertBreak()
{
#ifdef ENABLE_JS_EDITOR_LOG
nsAutoJSEditorLogLock logLock(mJSEditorLog);
if (mJSEditorLog)
mJSEditorLog->InsertBreak();
#endif // ENABLE_JS_EDITOR_LOG
nsCOMPtr<nsIDOMSelection> selection;
PRBool cancel= PR_FALSE;
// pre-process
nsEditor::GetSelection(getter_AddRefs(selection));
nsTextRulesInfo ruleInfo(nsTextEditRules::kInsertBreak);
nsresult result = mRules->WillDoAction(selection, &ruleInfo, &cancel);
if ((PR_FALSE==cancel) && (NS_SUCCEEDED(result)))
{
// For plainttext just pass newlines through
nsAutoString key;
key += '\n';
result = InsertText(key);
nsEditor::GetSelection(getter_AddRefs(selection));
result = mRules->DidDoAction(selection, &ruleInfo, result);
}
return result;
}
NS_IMETHODIMP nsTextEditor::EnableUndo(PRBool aEnable)
{
return nsEditor::EnableUndo(aEnable);
}
NS_IMETHODIMP nsTextEditor::Undo(PRUint32 aCount)
{
#ifdef ENABLE_JS_EDITOR_LOG
nsAutoJSEditorLogLock logLock(mJSEditorLog);
if (mJSEditorLog)
mJSEditorLog->Undo(aCount);
#endif // ENABLE_JS_EDITOR_LOG
nsCOMPtr<nsIDOMSelection> selection;
PRBool cancel= PR_FALSE;
// pre-process
nsEditor::GetSelection(getter_AddRefs(selection));
nsTextRulesInfo ruleInfo(nsTextEditRules::kUndo);
nsresult result = mRules->WillDoAction(selection, &ruleInfo, &cancel);
if ((PR_FALSE==cancel) && (NS_SUCCEEDED(result)))
{
result = nsEditor::Undo(aCount);
nsEditor::GetSelection(getter_AddRefs(selection));
result = mRules->DidDoAction(selection, &ruleInfo, result);
}
return result;
}
NS_IMETHODIMP nsTextEditor::CanUndo(PRBool &aIsEnabled, PRBool &aCanUndo)
{
return nsEditor::CanUndo(aIsEnabled, aCanUndo);
}
NS_IMETHODIMP nsTextEditor::Redo(PRUint32 aCount)
{
#ifdef ENABLE_JS_EDITOR_LOG
nsAutoJSEditorLogLock logLock(mJSEditorLog);
if (mJSEditorLog)
mJSEditorLog->Redo(aCount);
#endif // ENABLE_JS_EDITOR_LOG
nsCOMPtr<nsIDOMSelection> selection;
PRBool cancel= PR_FALSE;
// pre-process
nsEditor::GetSelection(getter_AddRefs(selection));
nsTextRulesInfo ruleInfo(nsTextEditRules::kRedo);
nsresult result = mRules->WillDoAction(selection, &ruleInfo, &cancel);
if ((PR_FALSE==cancel) && (NS_SUCCEEDED(result)))
{
result = nsEditor::Redo(aCount);
nsEditor::GetSelection(getter_AddRefs(selection));
result = mRules->DidDoAction(selection, &ruleInfo, result);
}
return result;
}
NS_IMETHODIMP nsTextEditor::CanRedo(PRBool &aIsEnabled, PRBool &aCanRedo)
{
return nsEditor::CanRedo(aIsEnabled, aCanRedo);
}
NS_IMETHODIMP nsTextEditor::BeginTransaction()
{
return nsEditor::BeginTransaction();
}
NS_IMETHODIMP nsTextEditor::EndTransaction()
{
return nsEditor::EndTransaction();
}
NS_IMETHODIMP nsTextEditor::MoveSelectionUp(nsIAtom *aIncrement, PRBool aExtendSelection)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTextEditor::MoveSelectionDown(nsIAtom *aIncrement, PRBool aExtendSelection)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTextEditor::MoveSelectionNext(nsIAtom *aIncrement, PRBool aExtendSelection)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTextEditor::MoveSelectionPrevious(nsIAtom *aIncrement, PRBool aExtendSelection)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTextEditor::SelectNext(nsIAtom *aIncrement, PRBool aExtendSelection)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTextEditor::SelectPrevious(nsIAtom *aIncrement, PRBool aExtendSelection)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTextEditor::SelectAll()
{
return nsEditor::SelectAll();
}
NS_IMETHODIMP nsTextEditor::BeginningOfDocument()
{
return nsEditor::BeginningOfDocument();
}
NS_IMETHODIMP nsTextEditor::EndOfDocument()
{
return nsEditor::EndOfDocument();
}
NS_IMETHODIMP nsTextEditor::ScrollUp(nsIAtom *aIncrement)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTextEditor::ScrollDown(nsIAtom *aIncrement)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTextEditor::ScrollIntoView(PRBool aScrollToBegin)
{
return nsEditor::ScrollIntoView(aScrollToBegin);
}
static NS_DEFINE_IID(kCFileWidgetCID, NS_FILEWIDGET_CID);
static NS_DEFINE_IID(kIFileWidgetIID, NS_IFILEWIDGET_IID);
NS_IMETHODIMP nsTextEditor::SaveDocument(PRBool saveAs, PRBool saveCopy)
{}
NS_IMETHODIMP nsTextEditor::Save()
{}
NS_IMETHODIMP nsTextEditor::SaveAs(PRBool aSavingCopy)
{}
NS_IMETHODIMP nsTextEditor::Cut()
{
return nsEditor::Cut();
}
NS_IMETHODIMP nsTextEditor::Copy()
{
return nsEditor::Copy();
}
NS_IMETHODIMP nsTextEditor::Paste()
{}
//
// Similar to that in nsEditor::Paste except that it does indentation:
//
NS_IMETHODIMP nsTextEditor::PasteAsQuotation()
{
#ifdef ENABLE_JS_EDITOR_LOG
nsAutoJSEditorLogLock logLock(mJSEditorLog);
if (mJSEditorLog)
mJSEditorLog->PasteAsQuotation();
#endif // ENABLE_JS_EDITOR_LOG
nsString stuffToPaste;
// Get Clipboard Service
nsIClipboard* clipboard;
nsresult rv = nsServiceManager::GetService(kCClipboardCID,
nsIClipboard::GetIID(),
(nsISupports **)&clipboard);
// Create generic Transferable for getting the data
nsCOMPtr<nsITransferable> trans;
rv = nsComponentManager::CreateInstance(kCTransferableCID, nsnull,
nsITransferable::GetIID(),
(void**) getter_AddRefs(trans));
if (NS_OK == rv)
{
// Get nsITransferable interface for getting the data from the clipboard
if (trans)
{
// We only handle plaintext pastes here
nsAutoString flavor(kTextMime);
trans->AddDataFlavor(&flavor);
// Get the Data from the clipboard
clipboard->GetData(trans);
// Now we ask the transferable for the data
// it still owns the data, we just have a pointer to it.
// If it can't support a "text" output of the data the call will fail
char *str = 0;
PRUint32 len;
if (NS_OK == trans->GetTransferData(&flavor, (void **)&str, &len)) {
// Make adjustments for null terminated strings
if (str && len > 0) {
// stuffToPaste is ready for insertion into the content
stuffToPaste.SetString(str, len);
}
}
}
}
nsServiceManager::ReleaseService(kCClipboardCID, clipboard);
return InsertAsQuotation(stuffToPaste);
}
NS_IMETHODIMP nsTextEditor::InsertAsQuotation(const nsString& aQuotedText)
{}
//
// Get the wrap width for the first PRE tag in the document.
// If no PRE tag, throw an error.
//
NS_IMETHODIMP nsTextEditor::GetBodyWrapWidth(PRInt32 *aWrapColumn)
{}
//
// Change the wrap width on the first <PRE> tag in this document.
// (Eventually want to search for more than one in case there are
// interspersed quoted text blocks.)
//
NS_IMETHODIMP nsTextEditor::SetBodyWrapWidth(PRInt32 aWrapColumn)
{}
NS_IMETHODIMP nsTextEditor::ApplyStyleSheet(const nsString& aURL)
{}
NS_IMETHODIMP nsTextEditor::OutputToString(nsString& aOutputString,
const nsString& aFormatType,
PRUint32 aFlags)
{}
NS_IMETHODIMP nsTextEditor::OutputToStream(nsIOutputStream* aOutputStream,
const nsString& aFormatType,
const nsString* aCharset,
PRUint32 aFlags)
{}
NS_IMETHODIMP nsTextEditor::SetTextPropertiesForNode(nsIDOMNode *aNode,
nsIDOMNode *aParent,
PRInt32 aStartOffset,
PRInt32 aEndOffset,
nsIAtom *aPropName,
const nsString *aAttribute,
const nsString *aValue)
{}
NS_IMETHODIMP nsTextEditor::MoveContentOfNodeIntoNewParent(nsIDOMNode *aNode,
nsIDOMNode *aNewParentNode,
PRInt32 aStartOffset,
PRInt32 aEndOffset)
{}
/* this should only get called if the only intervening nodes are inline style nodes */
NS_IMETHODIMP
nsTextEditor::SetTextPropertiesForNodesWithSameParent(nsIDOMNode *aStartNode,
PRInt32 aStartOffset,
nsIDOMNode *aEndNode,
PRInt32 aEndOffset,
nsIDOMNode *aParent,
nsIAtom *aPropName,
const nsString *aAttribute,
const nsString *aValue)
{}
//XXX won't work for selections that are not leaf nodes!
// should fix up the end points to make sure they are leaf nodes
NS_IMETHODIMP nsTextEditor::MoveContiguousContentIntoNewParent(nsIDOMNode *aStartNode,
PRInt32 aStartOffset,
nsIDOMNode *aEndNode,
PRInt32 aEndOffset,
nsIDOMNode *aGrandParentNode,
nsIDOMNode *aNewParentNode)
{}
/* this wraps every selected text node in a new inline style node if needed
the text nodes are treated as being unique -- each needs it's own style node
if the style is not already present.
each action has immediate effect on the content tree and resolved style, so
doing outermost text nodes first removes the need for interior style nodes in some cases.
XXX: need to code test to see if new style node is needed
*/
NS_IMETHODIMP
nsTextEditor::SetTextPropertiesForNodeWithDifferentParents(nsIDOMRange *aRange,
nsIDOMNode *aStartNode,
PRInt32 aStartOffset,
nsIDOMNode *aEndNode,
PRInt32 aEndOffset,
nsIDOMNode *aParent,
nsIAtom *aPropName,
const nsString *aAttribute,
const nsString *aValue)
{}
NS_IMETHODIMP nsTextEditor::RemoveTextPropertiesForNode(nsIDOMNode *aNode,
nsIDOMNode *aParent,
PRInt32 aStartOffset,
PRInt32 aEndOffset,
nsIAtom *aPropName,
const nsString *aAttribute)
{}
/* this should only get called if the only intervening nodes are inline style nodes */
NS_IMETHODIMP
nsTextEditor::RemoveTextPropertiesForNodesWithSameParent(nsIDOMNode *aStartNode,
PRInt32 aStartOffset,
nsIDOMNode *aEndNode,
PRInt32 aEndOffset,
nsIDOMNode *aParent,
nsIAtom *aPropName,
const nsString *aAttribute)
{}
NS_IMETHODIMP
nsTextEditor::RemoveTextPropertiesForNodeWithDifferentParents(nsIDOMNode *aStartNode,
PRInt32 aStartOffset,
nsIDOMNode *aEndNode,
PRInt32 aEndOffset,
nsIDOMNode *aParent,
nsIAtom *aPropName,
const nsString *aAttribute)
{}
TypeInState * nsTextEditor::GetTypeInState()
{}
NS_IMETHODIMP
nsTextEditor::SetTypeInStateForProperty(TypeInState &aTypeInState,
nsIAtom *aPropName,
const nsString *aAttribute,
const nsString *aValue)
{}
NS_IMETHODIMP nsTextEditor::SetBackgroundColor(const nsString& aColor)
{}
// This file should be rearranged to put all methods that simply call nsEditor together
NS_IMETHODIMP
nsTextEditor::CopyAttributes(nsIDOMNode *aDestNode, nsIDOMNode *aSourceNode)
{
return nsEditor::CopyAttributes(aDestNode, aSourceNode);
}
NS_IMETHODIMP
nsTextEditor::BeginComposition(void)
{}
NS_IMETHODIMP
nsTextEditor::SetCompositionString(const nsString& aCompositionString,nsIDOMTextRangeList* aTextRangeList)
{}
NS_IMETHODIMP
nsTextEditor::EndComposition(void)
{}
NS_IMETHODIMP
nsTextEditor::DebugUnitTests(PRInt32 *outNumTests, PRInt32 *outNumTestsFailed)
{
#ifdef DEBUG
if (!outNumTests || !outNumTestsFailed)
return NS_ERROR_NULL_POINTER;
TextEditorTest *tester = new TextEditorTest();
if (!tester)
return NS_ERROR_OUT_OF_MEMORY;
tester->Run(this, outNumTests, outNumTestsFailed);
delete tester;
return NS_OK;
#else
return NS_ERROR_NOT_IMPLEMENTED;
#endif
}
NS_IMETHODIMP
nsTextEditor::GetDocumentLength(PRInt32 *aCount)
{}

Some files were not shown because too many files have changed in this diff Show More