How Apps/SWF can call Apps - Bada Software and Hacking General

I was wondering, how Apps can call/start other Apps...
For instance internal Apps...
Also how we can modify for instance samsungApps.swf
Maybe we could create funny Theme with "App Starter"...
Best Regards

Code:
//Action tag #0
function dTrace(str)
{
++dtraceN;
this.dbg.text = this.dbg.text + ("\n" + dtraceN + " : " + str);
if (this.dbg.maxscroll > 1)
{
this.dbg.text = "";
}
}
function languageChange()
{
AppsClass.startSamsungApps();
}
function fontChange()
{
AppsClass.startSamsungApps();
}
function mouseEvent(type, mX, mY)
{
var __reg3 = undefined;
__reg3 = Gadget.SamsungApps.mouseClick(type, mX, mY);
if (type == "up" && __reg3 != true)
{
_root.dTrace("launch]Widget," + this);
}
}
function hasSound(type, mX, mY)
{
var __reg1 = undefined;
__reg1 = Gadget.SamsungApps.clickSound(type, mX, mY);
return __reg1;
}
function sendEvent(eventName, eventObj)
{
this.ExtendedEvents[eventName].addListener(eventObj);
listenerObj[eventName] = eventObj;
}
function removeEvent()
{
for (var __reg2 in listenerObj)
{
this.ExtendedEvents[__reg2].removeListener(listenerObj[__reg2]);
}
}
var dtraceN = 0;
this.ExtendedEvents = ExtendedEvents;
var AppsClass = Gadget.SamsungApps.getSamsungApps(this);
AppsClass.startSamsungApps();
this.widgetType = "launch";
this.launch = true;
var listenerObj = new Object();
This we can extract with Flash Decompiler...
Best Regards

Related

Kinetic Scroller

hello guys. just want to share this code to you
PHP:
using System;
namespace FBScroller
{
using System.Windows.Forms;
using System.Drawing;
public class KineticScroller
{
/*
* Kinetic Scroller
* by: Jayson Ragasa
* supports Windows Forms and WinMobile Forms
* ---------------------------------------
* Code stripped from: Implementing a smoothly animated ListBox
* http://www.codeproject.com/KB/list/SmoothListBox.aspx
*
* by: Fredrik Bornander
* http://www.codeproject.com/Members/Fredrik-Bornander
* ---------------------------------------
* Usage:
* make a panel1 on a form
* KineticScroller.HorizontalScroller ks = new KineticScroller.HorizontalScroller(panel1, this);
* make a new panel2 inside panel1
* KineticScroller.VerticalScroller ks2 = new KineticScroller.VerticalScroller(panel2, panel1);
*/
public class VerticalScroller
{
#region vars
private Point previousPoint = new Point();
private int draggedDistance = 0;
private float velocity = 0.0f;
private bool mouseIsDown = false;
private Control _ctl;
private Control _root;
Timer t = new Timer();
#endregion
#region animation stuff
private float dragDistanceFactor = 50.0f;
public float DragDistanceFactor
{
set
{
if (value < 1.0f)
throw new ArgumentException("DragDistanceFactor must be greater than or equal to 1.0", "value");
dragDistanceFactor = value;
}
}
private float maxVelocity = 9000.0f;
public float MaxVelocity
{
set
{
if (value < 1.0f)
throw new ArgumentException("MaxVelocity must be greater than or equal to 1.0", "value");
maxVelocity = value;
}
}
private float deaccelerationFactor = 0.9000f;
public float DeAccelerationFactor
{
set
{
if (value <= 0.0f || value >= 1.0f)
throw new ArgumentException("DeaccelerationFactor must fall within exclusive range 0.0 < value < 1.0", "value");
deaccelerationFactor = value;
}
}
private float snapBackFactor = 0.2f;
public float SnapBackFactor
{
set
{
if (value <= 0.0f || value >= 1.0f)
throw new ArgumentException("SnapBackFactor must fall within exclusive range 0.0 < value < 1.0", "value");
snapBackFactor = value;
}
}
#endregion
public VerticalScroller(Control control, Control root)
{
t.Interval = 50;
t.Enabled = true;
t.Tick += new EventHandler(t_Tick);
_ctl = control;
_ctl.Location = new Point(0, 0);
_ctl.MouseDown += new MouseEventHandler(_ctl_MouseDown);
_ctl.MouseMove += new MouseEventHandler(_ctl_MouseMove);
_ctl.MouseUp += new MouseEventHandler(_ctl_MouseUp);
_root = root;
}
void _ctl_MouseUp(object sender, MouseEventArgs e)
{
//if (e.Button == MouseButtons.Left)
{
velocity = Math.Min(Math.Max(dragDistanceFactor * draggedDistance, -maxVelocity), maxVelocity);
draggedDistance = 0;
Animate();
}
mouseIsDown = false;
}
void _ctl_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point absolutePoint = GetAbsolute(new Point(e.X, e.Y), _ctl, _root);
int delta = absolutePoint.Y - previousPoint.Y;
draggedDistance = delta;
Scroll(delta);
previousPoint = absolutePoint;
}
}
void _ctl_MouseDown(object sender, MouseEventArgs e)
{
mouseIsDown = true;
if (e.Button == MouseButtons.Left)
{
previousPoint = GetAbsolute(new Point(e.X, e.Y), _ctl, _root);
}
}
void t_Tick(object sender, EventArgs e)
{
Animate();
}
void Animate()
{
if (!mouseIsDown)
{
velocity *= deaccelerationFactor;
float elapsedTime = t.Interval / 1000.0f;
float deltaDistance = elapsedTime * velocity;
if (Math.Abs(deltaDistance) >= 1.0f)
{
Scroll((int)deltaDistance);
}
if (_ctl.Top != 0)
{
if (_ctl.Top > 0)
{
velocity = 0;
Scroll(-Math.Max(1, (int)(snapBackFactor * (float)(_ctl.Top))));
}
else
{
if (_ctl.Height > _root.ClientSize.Height)
{
int bottomPosition = _ctl.Top + _ctl.Height;
if (bottomPosition < _root.ClientSize.Height)
{
velocity = 0;
Scroll(Math.Max(1, (int)(snapBackFactor * (float)(_root.ClientSize.Height - bottomPosition))));
}
}
else
{
velocity = 0;
Scroll(Math.Max(1, -((int)(snapBackFactor * (float)_ctl.Top))));
}
}
}
}
}
void Scroll(int offset)
{
if (_ctl != null) _ctl.Top += offset;
}
private Point GetAbsolute(Point point, Control sourceControl, Control rootControl)
{
Point tempPoint = new Point();
for (Control iterator = sourceControl; iterator != rootControl; iterator = iterator.Parent)
{
tempPoint.Offset(iterator.Left, iterator.Top);
}
tempPoint.Offset(point.X, point.Y);
return tempPoint;
}
}
public class HorizontalScroller
{
#region vars
private Point previousPoint = new Point();
private int draggedDistance = 0;
private float velocity = 0.0f;
private bool mouseIsDown = false;
private Control _ctl;
private Control _root;
Timer t = new Timer();
#endregion
#region animation stuff
private float dragDistanceFactor = 50.0f;
public float DragDistanceFactor
{
set
{
if (value < 1.0f)
throw new ArgumentException("DragDistanceFactor must be greater than or equal to 1.0", "value");
dragDistanceFactor = value;
}
}
private float maxVelocity = 9000.0f;
public float MaxVelocity
{
set
{
if (value < 1.0f)
throw new ArgumentException("MaxVelocity must be greater than or equal to 1.0", "value");
maxVelocity = value;
}
}
private float deaccelerationFactor = 0.9000f;
public float DeAccelerationFactor
{
set
{
if (value <= 0.0f || value >= 1.0f)
throw new ArgumentException("DeaccelerationFactor must fall within exclusive range 0.0 < value < 1.0", "value");
deaccelerationFactor = value;
}
}
private float snapBackFactor = 0.2f;
public float SnapBackFactor
{
set
{
if (value <= 0.0f || value >= 1.0f)
throw new ArgumentException("SnapBackFactor must fall within exclusive range 0.0 < value < 1.0", "value");
snapBackFactor = value;
}
}
#endregion
public HorizontalScroller(Control control, Control root)
{
t.Interval = 50;
t.Enabled = true;
t.Tick += new EventHandler(t_Tick);
_ctl = control;
_ctl.Location = new Point(0, 0);
_ctl.MouseDown += new MouseEventHandler(_ctl_MouseDown);
_ctl.MouseMove += new MouseEventHandler(_ctl_MouseMove);
_ctl.MouseUp += new MouseEventHandler(_ctl_MouseUp);
_root = root;
}
void _ctl_MouseUp(object sender, MouseEventArgs e)
{
//if (e.Button == MouseButtons.Left)
{
velocity = Math.Min(Math.Max(dragDistanceFactor * draggedDistance, -maxVelocity), maxVelocity);
draggedDistance = 0;
Animate();
}
mouseIsDown = false;
}
void _ctl_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point absolutePoint = GetAbsolute(new Point(e.X, e.Y), _ctl, _root);
int delta = absolutePoint.X - previousPoint.X;
draggedDistance = delta;
Scroll(delta);
previousPoint = absolutePoint;
}
}
void _ctl_MouseDown(object sender, MouseEventArgs e)
{
mouseIsDown = true;
if (e.Button == MouseButtons.Left)
{
previousPoint = GetAbsolute(new Point(e.X, e.Y), _ctl, _root);
}
}
void t_Tick(object sender, EventArgs e)
{
Animate();
}
void Animate()
{
if (!mouseIsDown)
{
velocity *= deaccelerationFactor;
float elapsedTime = t.Interval / 1000.0f;
float deltaDistance = elapsedTime * velocity;
if (Math.Abs(deltaDistance) >= 1.0f)
{
Scroll((int)deltaDistance);
}
if (_ctl.Left != 0)
{
if (_ctl.Left > 0)
{
velocity = 0;
Scroll(-Math.Max(1, (int)(snapBackFactor * (float)(_ctl.Left))));
}
else
{
if (_ctl.Width > _root.ClientSize.Width)
{
int rightPosition = _ctl.Left + _ctl.Width;
if (rightPosition < _root.ClientSize.Width)
{
velocity = 0;
Scroll(Math.Max(1, (int)(snapBackFactor * (float)(_root.ClientSize.Width - rightPosition))));
}
}
else
{
velocity = 0;
Scroll(Math.Max(1, -((int)(snapBackFactor * (float)_ctl.Left))));
}
}
}
}
}
void Scroll(int offset)
{
if (_ctl != null) _ctl.Left += offset;
}
private Point GetAbsolute(Point point, Control sourceControl, Control rootControl)
{
Point tempPoint = new Point();
for (Control iterator = sourceControl; iterator != rootControl; iterator = iterator.Parent)
{
tempPoint.Offset(iterator.Left, iterator.Top);
}
tempPoint.Offset(point.X, point.Y);
return tempPoint;
}
}
}
}
I stipped his code and made a class version of his smooth scroller and modified to make a Horizontal and Vertical scroller
Did you do any updates to his code?

[Q] [.net cf]Loopback

Hey guys
I'm developing a little webserver for WM with the .net cf. it's easy and works fine as long as I don't try to access it from the same device it's running on. Nothing works: localhost,127.0.0.1 or even if I'm connected to a wifi network and I use this IP. Has anyone the solution for this issue?
ta you
a yeah I use the TcpListener-Class and I implemted some simple HTTP.
chabun
Code
Hey guys
Noone has an idea??
Here is the code which I use to setup the HttpListener and answer connections.
Code:
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using StedySoft.SenseSDK;
using System.Threading;
using System.IO;
namespace WebServer
{
public partial class ServerForm : Form
{
IPEndPoint local;
TcpListener listener;
private volatile bool stop;
private volatile bool handled;
SensePanelItem state;
SensePanelTextboxItem response;
Thread serverThread;
public ServerForm(IPEndPoint local)
{
InitializeComponent();
this.local = local;
SetupList();
}
private void SetupList()
{
SensePanelDividerItem infos = new SensePanelDividerItem("infd", "Infos");
mainList.AddItem(infos);
mainList.AddItem(new SensePanelItem("Local-Endpoint") { PrimaryText = "Local-Endpoint", SecondaryText = local.ToString() });
mainList.AddItem(state = new SensePanelItem("Status") { PrimaryText = "Status", SecondaryText = "Wird gestartet..." });
mainList.AddItem(new SensePanelDividerItem("Response", "Response"));
mainList.AddItem(response = new SensePanelTextboxItem("body") { LabelText = "HTML-Body, welcher auf Requests gesendet wird.", Text = "<span style =\"color:red;font-size:30pt\">It works!!</span>" });
mainList.AddItem(new SensePanelDividerItem("Requests", "Requests"));
}
private void StartServer()
{
if (listener != null)
{
StopServer(true);
}
listener = new TcpListener(local.Port);
listener.Start();
serverThread = new Thread(listen);
serverThread.IsBackground = true;
stop = false;
serverThread.Start();
state.SecondaryText = "Gestartet...";
}
private void listen()
{
while (!stop)
{
while (listener.Pending())
{
handled = false;
Thread handlingThread = new Thread(handler);
handlingThread.Start();
while (!handled)
Thread.Sleep(50);
}
Thread.Sleep(200);
}
}
private void handler()
{
// Get the current connection
TcpClient client = (TcpClient)this.Invoke(new Func<TcpClient>(listener.AcceptTcpClient));
IPEndPoint remote = (IPEndPoint)client.Client.RemoteEndPoint;
handled = true;
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
ReadHttpRequest(reader);
StreamWriter writer = new StreamWriter(stream);
StringBuilder response = new StringBuilder(); ;
StartHTML(response);
response.AppendLine((string)this.Invoke(new Func<IPEndPoint, string>(GetResponse), remote));
EndHTML(response);
WriteHTTPResponse(writer, response.Length);
writer.WriteLine(response.ToString());
writer.Flush();
stream.Close();
client.Close();
}
private void WriteHTTPResponse(StreamWriter writer, int length)
{
writer.WriteLine("HTTP/1.1 200 OK");
writer.WriteLine("Date: " + DateTime.Now.ToString());
writer.WriteLine("Content-Length: "+ length.ToString());
writer.WriteLine("Connection: close");
writer.WriteLine("Content-Type: text/html; charset=utf-8");
writer.WriteLine();
}
private void ReadHttpRequest(StreamReader reader)
{
string buffer = null;
while (buffer != "")
buffer = reader.ReadLine();
}
int counter = 0;
private string GetResponse(IPEndPoint remote)
{
counter++;
mainList.AddItem(new SensePanelItem(counter.ToString()) { PrimaryText = remote.ToString(), SecondaryText = "Response:" + counter.ToString() });
return response.Text;
}
private void EndHTML(StringBuilder writer)
{
writer.AppendLine("</body>");
writer.AppendLine("</html>");
}
private void StartHTML(StringBuilder writer)
{
writer.AppendLine("<?xml version=\"1.0\"?>");
writer.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
writer.AppendLine("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"de\" lang=\"de\">");
writer.AppendLine("<head>");
writer.AppendLine("<title>SmartWebServer</title>");
writer.AppendLine("<meta name=\"author\" content=\"Alexander Kayed\">");
writer.AppendLine("</head>");
writer.AppendLine("<body>");
}
private void StopServer(bool restart)
{
stop = true;
serverThread.Join();
if (restart)
StartServer();
}
private void ServerForm_Load(object sender, EventArgs e)
{
StartServer();
}
private void ServerForm_Closed(object sender, EventArgs e)
{
StopServer(false);
}
private void menuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
The user can choose the IPEndPoint(constructor), which the server will be bound to, in a prevouis form:
Code:
foreach (IPAddress ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
item = new SensePanelRadioItem(ip.ToString());
item.PrimaryText = ip.ToString();
item.SecondaryText = ip.AddressFamily.ToString();
item.Tag = ChoosedIp = ip;
item.OnStatusChanged += new SensePanelRadioItem.StatusEventHandler(item_OnStatusChanged);
IPList.AddItem(item);
}
So the user can choose between IPs I got from the DNS (e.g. 127.0.0.1, 192.168.0.1) and type a free (valid) port number (eg. 80, 8080, 8888)
Thanks for Your help!!
Still no answer...
I will post my experiences with this issue as long as I solved it - like small blog. Maybe some of you have the same problem...
I found another strange thing:
I'm able to connect to my Server from a TcpClient from another self-written App (own exectuable, different AppDomain):
Code:
void test()
{
Action<string> setText = new Action<string>(setTestText);
try
{
this.Invoke(setText, "Connect...");
TcpClient client = new TcpClient();
client.Connect(local);
this.Invoke(setText, "Connected...");
NetworkStream stream = client.GetStream();
StreamWriter writer = new StreamWriter(stream);
StreamReader reader = new StreamReader(stream);
writer.WriteLine();
writer.Flush();
this.Invoke(setText, "Read answer");
string buffer = reader.ReadToEnd();
this.Invoke(setText, "Test succeeded");
testing = false;
}
catch
{
this.Invoke(setText, "Test failed");
}
}
And I got a the right answer as well. It's strange, really strange that the browsers (IE,Opera etc.) can't loopback to it?

Need Developer Help - Form Refreshing

Hello,
i started to wrote my first WO7 applicatin.
I got following code:
Code:
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
BtnStart.Content = "Calculating...";
for (int i = 0; i < Pb1.Maximum; i++)
{
...
}
...
}
My Problem is that the content of the Button doesn't change to "Calculating". Even my Progressbar:
Code:
private void PbStep()
{
if (Pb1.Value == Pb1.Maximum)
{
Pb1.Value = 0;
MessageBox.Show("Progressbar Overflow");
}
else
{
Pb1.Value = Pb1.Value + 1;
}
}
It is wrapped in s loop, and the bar begins with 0 and then switsch to 100%, but i cant see the steps between.
I think i need a refresh command. in visual basic it is Me.Update();.
I tried many codes from google, but nothing helped. I hope some1 can help me.
many thank
Try
Code:
Dispatcher.BeginInvoke(() =>
{
BtnStart.Content = "Calculating...";
});
i did already try this. but now when i press the button, while calculation nothing happens, and after the calculation is finished, the button content changes to "calculating" and don't changes back to "start".
so i put the code in both parts and now i got the same as before. the button did not change its content
Code:
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
LblDuration.Text = "";
Dispatcher.BeginInvoke(() =>
{
BtnStart.Content = "Calculating...";
});
Pb1.Value = 0.0;
Pb1.Maximum = Max;
DateTime StartZeit = DateTime.Now;
for (int i = 0; i < Pb1.Maximum; i++)
{
PbStep();//Count Up PorgressBar
}
DateTime EndZeit = DateTime.Now;
TimeSpan GemesseneZeit = EndZeit - StartZeit;
LblDuration.Text = "Duration: " + GemesseneZeit.ToString();
Dispatcher.BeginInvoke(() =>
{
BtnStart.Content = "Start";
});
}
private void PbStep()
{
try
{
Pb1.Value = Pb1.Value + 1;
}
catch
{
Pb1.Value = 0;
MessageBox.Show("Progressbar Overflow");
}
}
But thank you for your help. any other ideas?
you really need to be looking at a background thread (background worker control may allow you do do this)
any tight loop like that will freeze the UI until the loop has finished
in the 'old days' a doevents within the loop itself would have been suffice but this is not good practice
HTH
Try this one, it does what you've trying to implement but using a correct way:
Code:
using System.Windows.Threading;
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
BtnStart.Content = "Calculating...";
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(100);
timer.Tick += (_, __) =>
{
// Here is replacement of your PbStep()
Pb1.Value++;
};
timer.Start();
}
i got it now this way:
Code:
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
LblDuration.Text = "Duration: Calculating...";
BtnStart.Content = "Wait";
DateTime StartZeit = DateTime.Now;
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(1);
timer.Tick += (_, __) =>
{
for (int i = 0; i < Pb1.Maximum; i++)
{
Pb1.Value++;
}
timer.Stop();
LblDuration.Text = "Duration: " + (DateTime.Now - StartZeit).ToString();
BtnStart.Content = "Start";
};
timer.Start();
}
It is half working. When i press Start, the button changes its content imediatly and after finishing the loop it return to its default content.
now i got 2 problems:
1. the progressbar isnt smooth jet
and the bigger one:
2. i wanted to create a benchmark programm an measure how long it takes to count a progressbar from 0 to 1million. now with the timer i dont have the real cpu speed because it is always waiting for the timer to tick. so the benchmark is sensless
@ cameronm:
I know the DoEvent command from other languages, but i wans able to use this in c#. i mainly programm in visual basic, cause this seems to be easy (In this case i would use Me.Update). I have heard from the Background worker, but never tried it. Maybe this can help.
I will do some google search and try to use the Background worker. I'll post again if i got new code
Thanks you all !
hello again
im now that far:
Code:
public partial class MainPage : PhoneApplicationPage
{
//Globale Variablen
private BackgroundWorker bw = new BackgroundWorker();
public int Max = 0;
// Konstruktor
public MainPage()
{
InitializeComponent();
Max = 500000;
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
if (bw.IsBusy != true)
{
LblDuration.Text = "";
BtnStart.Content = "Calculating...";
Pb1.Value = 0.0;
Pb1.Maximum = Max;
bw.RunWorkerAsync();
}
}
private void BtnStop_Click(object sender, System.Windows.RoutedEventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
DateTime StartZeit = DateTime.Now;
//Failure by any deklarion
//like int i = 0 or BtnStart.Content = "Calculating...";
for (int i = 0; i < Pb1.Maximum; i++)
{
if ((worker.CancellationPending == true)) //Abbruchbedingung
{
e.Cancel = true;
break;
}
else //Progressbedingung
{
PbStep();//Count Up PorgressBar
}
}
DateTime EndZeit = DateTime.Now;
TimeSpan GemesseneZeit = EndZeit - StartZeit;
LblDuration.Text = "Duration: " + GemesseneZeit.ToString();
BtnStart.Content = "Start";
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
this.LblStatus.Text = "Canceled!";
}
else if (!(e.Error == null))
{
this.LblStatus.Text = ("Error: " + e.Error.Message);
}
else
{
this.LblStatus.Text = "Done!";
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.LblPercentage.Text = (e.ProgressPercentage.ToString() + "%");
}
private void PbStep()
{
try
{
Pb1.Value = Pb1.Value + 1;
}
catch
{
Pb1.Value = 0;
MessageBox.Show("Progressbar Overflow");
}
}
In the DoWork Function i receive an error when i try to set a variable like int i=0.
The Failure:UnauthorizedAccessException: Invalid cross-thread access
i followed this instruction: http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx
but there they did the same. why did i have the error?
win98 said:
The Failure:UnauthorizedAccessException: Invalid cross-thread access
why did i have the error?
Click to expand...
Click to collapse
The exception you've got show exactly what's wrong: you are trying to access GUI thread variables from another (BackgroundWorker) thread.
Use Dispatcher.Invoke as I recommended to you a few posts above.
thank you sensboston. id dont understand why, because i just have one bgworker, but now it works
Code:
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
if (bw.IsBusy != true)
{
LblDuration.Text = "";
BtnStart.Content = "Calculating...";
Pb1.Value = 0.0;
Pb1.Maximum = Max;
bw.RunWorkerAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
DateTime StartZeit = DateTime.Now;
Dispatcher.BeginInvoke(() =>
{
LblDuration.Text = "";
BtnStart.Content = "Calculating...";
for (int i = 0; i < Pb1.Maximum; i++)
{
if ((worker.CancellationPending == true)) //Abbruchbedingung
{
e.Cancel = true;
break;
}
else //Progressbedingung
{
Pb1.Value = Pb1.Value + 1;
//PbStep();
}
}
DateTime EndZeit = DateTime.Now;
TimeSpan GemesseneZeit = EndZeit - StartZeit;
LblDuration.Text = "Duration: " + GemesseneZeit.ToString();
BtnStart.Content = "Start";
});
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.LblPercentage.Text = (e.ProgressPercentage.ToString() + "%");
}
Just my progressbar isnt running fluently. still just 0% (before calc) or 100% (after calc) and no steps between
win98 said:
Just my progressbar isnt running fluently. still just 0% (before calc) or 100% (after calc) and no steps between
Click to expand...
Click to collapse
It's simple, dear Watson: your code updating progress bar too fast, without delays needed for GUI updates
sensboston said:
It's simple, dear Watson: your code updating progress bar too fast, without delays needed for GUI updates
Click to expand...
Click to collapse
yep agree with this .. what you are actually doing in the loop is not enough for you to acutally see the progressbar update .. fast little things these phones of ours
yeah, this was the first i tryed, before posting in this forum.
delay() did not work in c#.
Application.DoEvents() should work if i can believe google, but visual studio says there is no definition for doevents().
So i used
Code:
Pb1.Value++;
System.Threading.Thread.Sleep(1);
after each progressbar.value++, but this either didnt work...
what is the secret?
win98 said:
yeah, this was the first i tryed, before posting in this forum.
delay() did not work in c#.
Application.DoEvents() should work if i can believe google, but visual studio says there is no definition for doevents().
So i used
Code:
Pb1.Value++;
System.Threading.Thread.Sleep(1);
after each progressbar.value++, but this either didnt work...
what is the secret?
Click to expand...
Click to collapse
1 millisecond will not be enough to slow it down either
Maybe try 1000 instead ..
something else i thought of too ..
you may want to think about your design
If a progress bar is going to just flash up and complete as what you are doing is too fast .. you need to think 'is a progress bar the right control to use'
if you are going to increase the amount of work your background thread is going to do then I would say keep the progress bar
If the background thread is going to be this quick always .. then maybe a label saying 'please wait' ... and then hide the label when done .. or something similar
i tried with 1000 ms but this progress bar isnt running.
@cameronm: i want to create a "benchmark app" where the cpu counts the progressbar to 1million and measures the time. the time measuring is working correctly. i just want to get a nice GUI with a running bar, like it runs when you download and install apps from the market.
i was very long googling and found commands like progressbar.PerfomStep(); like described here http://www.java2s.com/Code/CSharp/GUI-Windows-Form/ProgressBarinC.htm
this is also c#, but i cant perfom this command. did i miss some assembly, headers or so? or is it because im doint a windows phone form and that there are less command than in a normal windows application?
You want to make a Benchmark app and you actually used :System.Threading.Thread.Sleep(*int)...!
This is not Benchmarking.
Background Worker like any other ThreadTypeClass should report it's progress via the BackgroundWorker_ProgressChanged_Event(..args).
Inside the Event either u PerformStep() either you implement your own code logic.
If even after this the worker fills instanly like "cameronm" said above then consider making the backgroundworker's Job a bit heavier or leave the progressBar and even the seperated background thread Idea cause it is not Needed.
yes, i am not luck with using a sleep command
PerformStep() is not accepted by the compiler
so you mean just counting up is to "easy". what progress could be "heavier". now i understand what cameronm meant^^
in the evening i will try more difficult calculations like sqare and multiplication of integers. would that be heavy enough?
Typing from LG quantum
Try this: make your calculations in a for loop 1-100..at each loop make progressbar.value++ .
You should be calling ReportProgress and then updating the Progress Bar in the Progress Changed function.
See: http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx
@PG2G
the link you posted was exactly the source where i learned to implement the bw_worker. but with the command you told me i got an failure in the marked line (see source code comment). It says: InvalidOperationException: Operation has already been completed.
Code:
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
double a, b, c;
DateTime StartZeit = DateTime.Now;
Dispatcher.BeginInvoke(() =>
{
LblDuration.Text = "";
BtnStart.Content = "Calculating...";
for (int i = 0; i < Pb1.Maximum/100; i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
for (int m = 0; m < 10; m++)
{
a = 3547.23; //double
b = 2354.15; //double
c = (a * b) * (a * a * b);
}
Pb1.Value++;//PbStep();
worker.ReportProgress((i * 10)); //Failure here//
}
}
DateTime EndZeit = DateTime.Now;
TimeSpan GemesseneZeit = EndZeit - StartZeit;
LblDuration.Text = "Duration: " + GemesseneZeit.ToString();
BtnStart.Content = "Start";
});
}
@Freeboss
i tried it with your loop and a double calculation but it didnt work...
im going crazy, in vb i can do this in 10 minutes^^

Hook contacts data

Hello,
I'm currently working with Xposed and i need to restrict access of contacts to applications installed on smartphone i allready tried some codes but not working anyone can help me?
try {
// final Class<?> cResolver = findClass("android.content.ContentResolver",lpparam.classLoader);
//android.content.ContentProviderClient
final Class<?> cResolver = findClass("android.content.ContentResolver",lpparam.classLoader);
XposedBridge.log("<--------ENTROUUUUUUUUUUUUUU COntentResolver----------->: " + lpparam.packageName);
XposedBridge.hookAllMethods(cResolver, "query", new XC_MethodHook() {
@SuppressLint("DefaultLocale")
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
XposedBridge.log(" Hooked method: " + param.method);
XposedBridge.log(" uri=" + param.args[0]);
String uri = ((Uri) param.args[0]).toString().toLowerCase();
String[] projection = (param.args[1] instanceof String[] ? (String[]) param.args[1] :null);
if (uri.startsWith("content://com.android.contacts/contacts/name_phone_or_email")) {
} else if (uri.startsWith("content://com.android.contacts/") && !uri.equals("content://com.android.contacts/")) {
XposedBridge.log("JOAAAAAAAAAAAAAAAOOOOOOOOOOOOOOOOOOOO 111111111111111111");
String[] components = uri.replace("content://com.android.", "").split("/");
String methodName = components[0] + "/" + components[1].split("\\?")[0];
if (methodName.equals("contacts/contacts") || methodName.equals("contacts/data") || methodName.equals("contacts/phone_lookup") || methodName.equals("contacts/raw_contacts")){
XposedBridge.log("JOAAAAAAAAAAAAAAAOOOOOOOOOOOOOOOOOOOO 22222222222222");
int urlid = -1;
if ((methodName.equals("contacts/contacts") || methodName.equals("contacts/phone_lookup")) && components.length > 2 && TextUtils.isDigitsOnly(components[2])){
urlid = Integer.parseInt(components[2]);
boolean added = false;
if (projection != null && urlid < 0) {
List<String> listProjection = new ArrayList<String>();
listProjection.addAll(Arrays.asList(projection));
String cid = getIdForUri(uri);
if (cid != null && !listProjection.contains(cid)) {
XposedBridge.log("ENTROUU nesta merda do CID");
added = true;
listProjection.add(cid);
}
param.args[1] = listProjection.toArray(new String[0]);
}
if (added)
XposedBridge.log("ENTROUU nesta merda do added");
param.setObjectExtra("column_added", added);
}
}
}
}
@SuppressLint("DefaultLocale")
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
if (param.args.length > 1 && param.args[0] instanceof Uri && param.getResult() != null) {
String uri = ((Uri) param.args[0]).toString().toLowerCase();
String[] projection = (param.args[1] instanceof String[] ? (String[]) param.args[1] : null);
String selection = (param.args[2] instanceof String ? (String) param.args[2] : null);
Cursor cursor = (Cursor) param.getResult();
if (uri.startsWith("content://com.android.contacts/")&& !uri.equals("content://com.android.contacts/")) {
// Contacts provider: allow selected contacts
String[] components = uri.replace("content://com.android.", "").split("/");
String methodName = components[0] + "/" + components[1].split("\\?")[0];
if (methodName.equals("contacts/contacts") || methodName.equals("contacts/data") || methodName.equals("contacts/phone_lookup") || methodName.equals("contacts/raw_contacts")) {
int urlid = -1;
if ((methodName.equals("contacts/contacts") || methodName.equals("contacts/phone_lookup")) && components.length > 2 && TextUtils.isDigitsOnly(components[2])){
urlid = Integer.parseInt(components[2]);
}
// Modify column names back
Object column_added = param.getObjectExtra("column_added");
boolean added = (column_added == null ? false : (Boolean) param.getObjectExtra("column_added"));
List<String> listColumn = new ArrayList<String>();
listColumn.addAll(Arrays.asList(cursor.getColumnNames()));
if (added) listColumn.remove(listColumn.size() - 1);
MatrixCursor result = new MatrixCursor(listColumn.toArray(new String[0]));
// Filter rows
String cid = getIdForUri(uri);
int iid = (cid == null ? -1 : cursor.getColumnIndex(cid));
if (iid >= 0 || urlid >= 0)
while (cursor.moveToNext()) {
copyColumns(cursor, result, listColumn.size());
}
else{
XposedBridge.log("ENTROUUUU NO ELSE");
XposedBridge.log("ID missing URI=" + uri + " added=" + added + "/" + cid
+ " columns=" + TextUtils.join(",", cursor.getColumnNames()) + " projection="
+ (projection == null ? "null" : TextUtils.join(",", projection)) + " selection="
+ selection);
}
result.respond(cursor.getExtras());
param.setResult(result);
cursor.close();
}else{
methodName = null;
if (uri.startsWith("content://com.android.contacts/profile"))
methodName = "contacts/profile";
else
methodName = "ContactsProvider2"; // fall-back
if (methodName != null){
// Return empty cursor
MatrixCursor result = new MatrixCursor(cursor.getColumnNames());
result.respond(cursor.getExtras());
XposedBridge.log(cursor.getExtras().toString());
param.setResult(result);
cursor.close();
}
}
}
}
}
});
} catch (Throwable t) {
throw t;
}

GWD loads watchface.xml this way (java source inside)

This is from the GWD file : C:\Program Files (x86)\GearWatchDesigner\plugins\com.samsung.gwd_1.6.2.201810300802.jar
This is a Java package. When looking inside with a "Java decompiler" (free download), find the loadXml.class and you'll see the following code. Once we analyze this, I think we can kind of figure out the schema.
Code:
package com.samsung.gwd;
import com.samsung.gwd.gef.models.ActionConfig;
import com.samsung.gwd.gef.models.ActionConfigEnum.ACTION_STATE;
import com.samsung.gwd.gef.models.Condition;
import com.samsung.gwd.gef.models.ModelAnimation;
import com.samsung.gwd.gef.models.ModelBackground;
import com.samsung.gwd.gef.models.ModelComponent;
import com.samsung.gwd.gef.models.ModelDigitalclock;
import com.samsung.gwd.gef.models.ModelGroup;
import com.samsung.gwd.gef.models.ModelHand;
import com.samsung.gwd.gef.models.ModelImage;
import com.samsung.gwd.gef.models.ModelIndex;
import com.samsung.gwd.gef.models.ModelRoot;
import com.samsung.gwd.gef.models.ModelText;
import com.samsung.gwd.source.Source;
import com.samsung.gwd.ui.dialog.bitmapfont.BitmapFont;
import com.samsung.gwd.utils.RM;
import com.samsung.gwd.utils.Util;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
public class LoadXml
{
public static final int TIME_ONE_MINUTE = 900;
public static final int TIME_ONE_HOUR = 54000;
public static final double PLATFORM_HOUR_MINUTE_CORRECTION = 0.005D;
Project project;
ModelRoot root;
String path;
Document doc;
String projectDir;
int width;
int height;
public LoadXml(String path, String name, Project project)
{
this.path = path;
File file = new File(path + name);
this.project = project;
this.projectDir = project.getProjectDir();
if (file.isFile())
{
DocumentBuilderFactory docBuildFact = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder docBuild = docBuildFact.newDocumentBuilder();
this.doc = docBuild.parse(file);
this.doc.getDocumentElement().normalize();
NodeList watchface = this.doc.getElementsByTagName("watchface");
Node watchfaceNode = watchface.item(0);
this.width = Integer.parseInt(((Element)watchfaceNode).getAttribute("width"));
this.height = Integer.parseInt(((Element)watchfaceNode).getAttribute("height"));
NodeList groupsList = this.doc.getElementsByTagName("groups");
for (int i = 0; i < groupsList.getLength(); i++)
{
Node groupsNode = groupsList.item(i);
processGroups((Element)groupsNode);
}
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
Application.LOGGER.error("Loading XML failed : " + path + name);
}
}
void processGroups(Element groupsElmt)
{
if (groupsElmt.getAttribute("type").equals("ambient"))
{
this.project.initLowBitAmbientMode();
this.root = this.project.getAmbientLowRoot();
}
else if (groupsElmt.getAttribute("type").equals("ambient-fullcolor"))
{
this.project.initHighColorAmbientMode();
this.root = this.project.getAmbientHighRoot();
}
else if (groupsElmt.getAttribute("type").equals("current"))
{
this.root = this.project.getModelRoot();
}
else
{
this.root = this.project.getNormalRoot();
}
NodeList groupList = groupsElmt.getElementsByTagName("group");
for (int j = 0; j < groupList.getLength(); j++)
{
Node groupNode = groupList.item(j);
processGroup((Element)groupNode);
}
}
void processGroup(Element groupElm)
{
ModelGroup group = null;
ActionConfig actionConf = null;
String tmpStr = groupElm.getAttribute("x");
if (!groupElm.getAttribute("name").startsWith("__DEFAULT_GROUP")) {
if (!tmpStr.isEmpty())
{
group = new ModelGroup(this.root);
group.setRect(Integer.parseInt(groupElm.getAttribute("x")), Integer.parseInt(groupElm.getAttribute("y")),
Integer.parseInt(groupElm.getAttribute("width")), Integer.parseInt(groupElm.getAttribute("height")));
}
else
{
group = new ModelGroup(this.root);
group.setRect(0, 0, this.width, this.height);
}
}
Point groupLoc;
Point groupLoc;
if (!groupElm.getAttribute("x").isEmpty()) {
groupLoc = new Point(Integer.parseInt(groupElm.getAttribute("x")), Integer.parseInt(groupElm.getAttribute("y")));
} else {
groupLoc = new Point(0, 0);
}
NodeList groupChildList = groupElm.getChildNodes();
for (int i = 0; i < groupChildList.getLength(); i++)
{
Node childNode = groupChildList.item(i);
if ((childNode.getNodeType() == 1) && (childNode.getNodeName().equals("action")))
{
Element childElm = (Element)childNode;
String on_event = childElm.getAttribute("on_event");
if (on_event.equals("tap"))
{
String type = childElm.getAttribute("type");
if (type.equals("launch"))
{
NodeList launchList = childElm.getElementsByTagName("launch");
if (launchList.getLength() != 0)
{
Node launchNode = launchList.item(0);
String appid = ((Element)launchNode).getAttribute("app_id");
if (appid.isEmpty()) {
appid = ((Element)launchNode).getAttribute("preset");
}
if (actionConf != null) {
break;
}
actionConf = new ActionConfig(DeviceSpec.GEAR_S2.getOpenAppTable());
actionConf.setActionState("Open App");
actionConf.setSelectAppId(appid);
}
}
else if (type.equals("image-set-show-next"))
{
if (actionConf != null) {
break;
}
actionConf = new ActionConfig(DeviceSpec.GEAR_S2.getOpenAppTable());
actionConf.setActionState("Change Image");
}
}
}
}
for (int i = 0; i < groupChildList.getLength(); i++)
{
Node childNode = groupChildList.item(i);
if (childNode.getNodeType() == 1)
{
Element childElmnt = (Element)childNode;
if (childNode.getNodeName().equals("part"))
{
ModelComponent model = processPart(childElmnt, group, actionConf);
if (model != null)
{
model.setLocation(model.getLocation().x + groupLoc.x, model.getLocation().y + groupLoc.y);
try
{
if (actionConf == null) {
break;
}
actionConf.setModel(model);
model.setActionConfig(actionConf);
model.setButton(true);
}
catch (Exception e)
{
e.printStackTrace();
if (group == null)
{
this.root.removeChild(model); continue;
}
group.removeChild(model);
continue;
}
}
}
else if (childNode.getNodeName().equals("condition"))
{
ModelComponent model = processCondition(childElmnt, group, 0, 0, null, actionConf);
if (model != null)
{
model.setLocation(model.getLocation().x + groupLoc.x, model.getLocation().y + groupLoc.y);
try
{
if (group == null) {
this.root.addChild(model);
} else {
group.addChild(model);
}
if (actionConf == null) {
break;
}
actionConf.setModel(model);
model.setActionConfig(actionConf);
model.setButton(true);
}
catch (Exception e)
{
e.printStackTrace();
if (group == null) {
this.root.removeChild(model);
} else {
group.removeChild(model);
}
}
}
}
}
}
}
ModelComponent processPart(Element partElmt, ModelGroup group, ActionConfig actionConf)
{
Rectangle partRect = null;
String tmpStr = partElmt.getAttribute("x");
if (!tmpStr.isEmpty()) {
partRect = new Rectangle(Integer.parseInt(tmpStr),
Integer.parseInt(partElmt.getAttribute("y")),
Integer.parseInt(partElmt.getAttribute("width")),
Integer.parseInt(partElmt.getAttribute("height")));
}
String type = partElmt.getAttribute("type");
if (type.equals("image")) {
return processPartImage(partElmt, group, partRect, actionConf);
}
if (type.equals("text")) {
return processPartText(partElmt, group, partRect);
}
if (!type.equals("draw")) {
Application.LOGGER.error("Not supporeted part type : " + type);
}
return null;
}
ModelComponent processPartImage(Element partElmt, ModelGroup group, Rectangle partRect, ActionConfig actionConf)
{
ModelImage obj = null;
boolean isHands = false;
boolean isBackground = false;
boolean isIndex = false;
ModelComponent parent;
ModelComponent parent;
if (group != null) {
parent = group;
} else {
parent = this.root;
}
NodeList partAttrList = null;
Node partAttrNode = null;
Element partAttrElmnt = null;
Element metaElmnt = null;
partAttrList = partElmt.getElementsByTagName("metadata");
if (partAttrList.getLength() != 0)
{
for (int i = 0; i < partAttrList.getLength(); i++)
{
partAttrNode = partAttrList.item(i);
metaElmnt = (Element)partAttrNode;
String tmpStr = metaElmnt.getAttribute("type");
if (tmpStr.equals("hands")) {
isHands = true;
} else if (tmpStr.equals("background")) {
isBackground = true;
} else if (tmpStr.equals("index")) {
isIndex = true;
}
}
}
else
{
partAttrList = partElmt.getElementsByTagName("rotation");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
if ((partAttrElmnt.getAttribute("source").equals("hour0-23.minute")) ||
(partAttrElmnt.getAttribute("source").equals("minute"))) {
isHands = true;
}
}
}
partAttrList = partElmt.getElementsByTagName("image-set");
if ((partAttrList.getLength() == 0) || ((actionConf != null) && (actionConf.getActionState() == ActionConfigEnum.ACTION_STATE.CHANGE_IMAGE)))
{
String baseName = null;
if ((actionConf != null) && (actionConf.getActionState() == ActionConfigEnum.ACTION_STATE.CHANGE_IMAGE))
{
String projResDir = new String(this.project.getProjectDir() + BuildConfig.PATH_XML);
partAttrList = partElmt.getElementsByTagName("image-set");
if (partAttrList.getLength() != 0)
{
int changeNum = 0;
NodeList imageSetChildList = partAttrList.item(0).getChildNodes();
for (int nodeIndex = 0; nodeIndex < imageSetChildList.getLength(); nodeIndex++)
{
Node imageSetChildNode = imageSetChildList.item(nodeIndex);
if (imageSetChildNode.getNodeType() == 1) {
if (imageSetChildNode.getNodeName().equals("image"))
{
Element imageElmnt = (Element)imageSetChildNode;
if (nodeIndex == 0)
{
baseName = imageElmnt.getTextContent();
}
else
{
if ((imageElmnt.getTextContent() == "") || (imageElmnt.getTextContent().compareTo(baseName) == 0))
{
actionConf.setChangeImage(null, changeNum, null);
}
else
{
String str_des = new String(imageElmnt.getTextContent());
if (System.getProperty("os.name").contains("Windows")) {
while (str_des.contains("/")) {
str_des = str_des.replace("/", File.separator);
}
}
actionConf.setChangeImage(RM.getImage(projResDir + str_des),
changeNum, projResDir + str_des);
}
changeNum++;
}
}
}
}
}
Rectangle tempRect = new Rectangle(partRect);
if (isHands) {
obj = new ModelHand(parent, this.path, baseName);
} else if (isBackground) {
obj = new ModelBackground(parent, this.path, baseName);
} else {
obj = new ModelImage(parent, this.path, baseName);
}
obj.setRect(tempRect);
}
else
{
partAttrList = partElmt.getElementsByTagName("image");
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
NodeList partAttrChildList = partAttrNode.getChildNodes();
Rectangle tempRect = new Rectangle(partRect);
if (partAttrChildList.getLength() == 1)
{
if (isHands)
{
obj = new ModelHand(parent, this.path, partAttrElmnt.getTextContent());
obj.setRect(tempRect);
}
else if (isBackground)
{
obj = new ModelBackground(parent, this.path, partAttrElmnt.getTextContent());
obj.setRect(tempRect);
}
else if (isIndex)
{
String tmpStr = metaElmnt.getAttribute("image");
if (!tmpStr.isEmpty())
{
obj = new ModelIndex(parent, this.path, tmpStr);
obj.setRect(tempRect);
((ModelIndex)obj).setOriginalRect(new Rectangle(Integer.parseInt(metaElmnt.getAttribute("x")),
Integer.parseInt(metaElmnt.getAttribute("y")),
Integer.parseInt(metaElmnt.getAttribute("width")),
Integer.parseInt(metaElmnt.getAttribute("height"))));
}
else
{
obj = new ModelIndex(parent, this.path, partAttrElmnt.getTextContent());
obj.setRect(tempRect);
}
tmpStr = metaElmnt.getAttribute("range");
if (tmpStr.isEmpty()) {
return null;
}
((ModelIndex)obj).setRange(0.0D, Integer.parseInt(tmpStr));
tmpStr = metaElmnt.getAttribute("number");
((ModelIndex)obj).setNumber(Integer.parseInt(tmpStr));
((ModelIndex)obj).apply();
((ModelIndex)obj).setRect(tempRect);
}
else
{
obj = new ModelImage(parent, this.path, partAttrElmnt.getTextContent());
obj.setRect(tempRect);
}
}
else {
Application.LOGGER.error("LoadXml : Implement me - image condition, length=" + partAttrChildList.getLength());
}
}
if (obj != null)
{
partAttrList = partElmt.getElementsByTagName("color");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
String tmpStr = partAttrElmnt.getAttribute("a");
if (!tmpStr.isEmpty())
{
tmpStr = partAttrElmnt.getAttribute("r");
if (!tmpStr.isEmpty())
{
obj.setFilterEnable(true);
float[] hsl = Color.RGBtoHSB(Integer.parseInt(partAttrElmnt.getAttribute("r")),
Integer.parseInt(partAttrElmnt.getAttribute("g")),
Integer.parseInt(partAttrElmnt.getAttribute("b")), null);
obj.setHue((int)(hsl[0] * 360.0F - 180.0F));
obj.setSaturation((int)(hsl[1] * 200.0F - 100.0F));
obj.setLightness((int)(hsl[2] * 200.0F - 100.0F));
obj.setAlpha(Integer.parseInt(partAttrElmnt.getAttribute("a")));
}
else
{
obj.setAlpha(Integer.parseInt(partAttrElmnt.getAttribute("a")));
}
}
}
partAttrList = partElmt.getElementsByTagName("rotation");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
String source = partAttrElmnt.getAttribute("source");
if (!source.isEmpty())
{
if (isHands)
{
ModelHand hand = (ModelHand)obj;
hand.setSource(Source.findById(source));
if (!partElmt.getAttribute("x").isEmpty())
{
hand.setPivot(Integer.parseInt(partAttrElmnt.getAttribute("center_x")) +
Integer.parseInt(partElmt.getAttribute("x")),
Integer.parseInt(partAttrElmnt.getAttribute("center_y")) +
Integer.parseInt(partElmt.getAttribute("y")));
hand.setStartAngle(Double.parseDouble(partAttrElmnt.getAttribute("start_angle")));
hand.setEndAngle(Double.parseDouble(partAttrElmnt.getAttribute("end_angle")));
hand.setStartValue(Double.parseDouble(partAttrElmnt.getAttribute("start_value")));
hand.setEndValue(Double.parseDouble(partAttrElmnt.getAttribute("end_value")));
}
else
{
if (group == null) {
hand.setPivot(Integer.parseInt(partAttrElmnt.getAttribute("center_x")),
Integer.parseInt(partAttrElmnt.getAttribute("center_y")));
}
hand.setStartAngle(Double.parseDouble(partAttrElmnt.getAttribute("start_angle")));
hand.setEndAngle(Double.parseDouble(partAttrElmnt.getAttribute("end_angle")));
hand.setStartValue(Double.parseDouble(partAttrElmnt.getAttribute("start_value")));
hand.setEndValue(Double.parseDouble(partAttrElmnt.getAttribute("end_value")));
}
if (partAttrElmnt.getAttribute("animation").equals("tick"))
{
hand.setTensionFrame(Integer.parseInt(partAttrElmnt.getAttribute("tick_frame")) / 2);
hand.setTensionAngle(Double.parseDouble(partAttrElmnt.getAttribute("tick_angle")));
hand.setTension((int)(hand.getTensionAngle() * 100.0D / 6.0D));
hand.setTensionEnabled(true);
}
if (source.equals("hour0-11.minute"))
{
hand.setSource(Source.findById("hour0-23.minute"));
if (hand.getStartAngle() < hand.getEndAngle()) {
hand.setEndAngle(hand.getEndAngle() + 360.0D);
} else {
hand.setEndAngle(hand.getEndAngle() - 360.0D);
}
}
}
}
else if (!partAttrElmnt.getAttribute("angle").isEmpty()) {
if (Util.checkExprTag(partAttrElmnt.getAttribute("angle"))) {
obj.setAngle(Util.removeExprTag(partAttrElmnt.getAttribute("angle")));
} else {
obj.setAngle(Double.parseDouble(partAttrElmnt.getAttribute("angle")));
}
}
}
}
}
else
{
partAttrList = partElmt.getElementsByTagName("image-set");
if (partAttrList.getLength() != 0)
{
ModelAnimation ani = new ModelAnimation(parent);
int frameNum = 0;
ani.setRect(partRect);
NodeList imageSetChildList = partAttrList.item(0).getChildNodes();
for (int nodeIndex = 0; nodeIndex < imageSetChildList.getLength(); nodeIndex++)
{
Node imageSetChildNode = imageSetChildList.item(nodeIndex);
if (imageSetChildNode.getNodeType() == 1)
{
if (imageSetChildNode.getNodeName().equals("image"))
{
Element imageElmnt = (Element)imageSetChildNode;
ModelImage frameItem = new ModelImage(ani, this.path, imageElmnt.getTextContent());
frameItem.setRect(0, 0, partRect.width, partRect.height);
frameItem.setId("Frame " + (nodeIndex + 1));
frameItem.getCondition().deleteAll();
frameItem.getCondition().addItem(frameNum, frameNum + 1);
}
frameNum++;
}
}
partAttrList = partElmt.getElementsByTagName("color");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
String tmpStr = partAttrElmnt.getAttribute("a");
if (!tmpStr.isEmpty()) {
ani.setAlpha(Integer.parseInt(partAttrElmnt.getAttribute("a")));
}
}
partAttrList = partElmt.getElementsByTagName("rotation");
if (partAttrList.getLength() != 0)
{
partAttrElmnt = (Element)partAttrList.item(0);
if (!partAttrElmnt.getAttribute("angle").isEmpty()) {
if (Util.checkExprTag(partAttrElmnt.getAttribute("angle"))) {
ani.setAngle(Util.removeExprTag(partAttrElmnt.getAttribute("angle")));
} else {
ani.setAngle(Double.parseDouble(partAttrElmnt.getAttribute("angle")));
}
}
}
return ani;
}
}
return obj;
}
Con't
Code:
ModelComponent processPartText(Element partElmt, ModelGroup group, Rectangle partRect)
{
String tmpStr = null;
boolean isDigitalclock = false;
NodeList partAttrList = null;
Node partAttrNode = null;
Element partAttrElmnt = null;
partAttrList = partElmt.getElementsByTagName("metadata");
if (partAttrList.getLength() != 0) {
for (int i = 0; i < partAttrList.getLength(); i++)
{
partAttrNode = partAttrList.item(i);
partAttrElmnt = (Element)partAttrNode;
tmpStr = partAttrElmnt.getAttribute("type");
if (tmpStr.equals("digitalclock")) {
isDigitalclock = true;
}
}
}
Rectangle tempRect = new Rectangle(partRect);
if (group != null)
{
tempRect.x += group.getRect().x;
tempRect.y += group.getRect().y;
}
ModelComponent parent;
ModelComponent parent;
if (group != null) {
parent = group;
} else {
parent = this.root;
}
ModelText mText;
ModelText mText;
if (isDigitalclock) {
mText = new ModelDigitalclock(parent);
} else {
mText = new ModelText(parent);
}
mText.setRect(partRect);
partAttrList = partElmt.getElementsByTagName("style");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
tmpStr = partAttrElmnt.getAttribute("typeface");
if (!tmpStr.isEmpty()) {
mText.setFontName(tmpStr);
}
tmpStr = partAttrElmnt.getAttribute("size");
mText.setFont(mText.getFontName(), Integer.parseInt(tmpStr));
tmpStr = partAttrElmnt.getAttribute("style");
if (!tmpStr.isEmpty())
{
if (tmpStr.equals("Bold")) {
mText.setFontStyle(1);
}
mText.setFontStyle(mText.getFontStyle());
}
tmpStr = partAttrElmnt.getAttribute("filename");
if (!tmpStr.isEmpty())
{
mText.setFontName(tmpStr);
mText.setCustomFont(tmpStr, mText.getFontSize());
}
}
partAttrList = partElmt.getElementsByTagName("color");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
tmpStr = partAttrElmnt.getAttribute("r");
if (!tmpStr.isEmpty())
{
mText.setColor(RM.getColor(Integer.parseInt(partAttrElmnt.getAttribute("r")),
Integer.parseInt(partAttrElmnt.getAttribute("g")),
Integer.parseInt(partAttrElmnt.getAttribute("b"))));
mText.setAlpha(Integer.parseInt(partAttrElmnt.getAttribute("a")));
}
else
{
tmpStr = partAttrElmnt.getAttribute("a");
if (!tmpStr.isEmpty()) {
mText.setAlpha(Integer.parseInt(partAttrElmnt.getAttribute("a")));
}
}
}
partAttrList = partElmt.getElementsByTagName("icu-skeleton");
int j;
Locale[] pcLocales;
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
mText.setText(partAttrElmnt.getTextContent());
String strLocales = partAttrElmnt.getAttribute("locale");
if (!strLocales.isEmpty())
{
String[] tokens = strLocales.split(";");
List<Locale> locales = new ArrayList();
String[] arrayOfString1;
j = (arrayOfString1 = tokens).length;
for (int i = 0; i < j; i++)
{
String token = arrayOfString1[i];
pcLocales = Locale.getAvailableLocales();
for (int i = 0; i < pcLocales.length; i++)
{
String str = pcLocales[i].getLanguage() + "_" + pcLocales[i].getCountry();
if (token.equals(str))
{
locales.add(pcLocales[i]);
break;
}
}
}
mText.setLocale(locales);
}
}
partAttrList = partElmt.getElementsByTagName("text");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
String strAlign = partAttrElmnt.getAttribute("align");
if (!strAlign.isEmpty()) {
if (strAlign.equals("left")) {
mText.setAlignment(16384);
} else if (strAlign.equals("right")) {
mText.setAlignment(131072);
} else {
mText.setAlignment(16777216);
}
}
String strLocales = partAttrElmnt.getAttribute("locale");
if (!strLocales.isEmpty())
{
String[] tokens = strLocales.split(";");
List<Locale> locales = new ArrayList();
int k = (pcLocales = tokens).length;
for (j = 0; j < k; j++)
{
Object token = pcLocales[j];
Locale[] pcLocales = Locale.getAvailableLocales();
for (int i = 0; i < pcLocales.length; i++)
{
String str = pcLocales[i].getLanguage() + "_" + pcLocales[i].getCountry();
if (((String)token).equals(str))
{
locales.add(pcLocales[i]);
break;
}
}
}
mText.setLocale(locales);
}
if (partAttrElmnt.getElementsByTagName("format").getLength() != 0)
{
String front = null;String source = null;String back = null;
NodeList textChildList = partAttrElmnt.getChildNodes();
for (int i = 0; i < 2; i++)
{
Node textChildNode = textChildList.item(0);
if (textChildNode.getNodeType() == 1)
{
Element textChildElmnt = (Element)textChildNode;
if (textChildElmnt.getTagName().equals("format")) {
break;
}
textChildList = textChildElmnt.getChildNodes();
}
}
boolean isFormatProcessed = false;
for (int i = 0; i < textChildList.getLength(); i++)
{
Node textChildNode = textChildList.item(i);
if (textChildNode.getNodeType() == 1)
{
Element textChildElmnt = (Element)textChildNode;
if (textChildElmnt.getTagName().equals("format"))
{
source = textChildElmnt.getAttribute("source");
isFormatProcessed = true;
}
}
else if (textChildNode.getNodeType() == 3)
{
Text textChildElmnt = (Text)textChildNode;
tmpStr = textChildElmnt.getTextContent();
if (!tmpStr.isEmpty()) {
if (!isFormatProcessed) {
front = tmpStr;
} else {
back = tmpStr;
}
}
}
}
Application.LOGGER.info(String.format("contents = %s, %s, %s", new Object[] { front, source, back }));
mText.setSource(Source.findById(source));
mText.setFormat(front, back);
}
else
{
tmpStr = partAttrElmnt.getTextContent();
Application.LOGGER.info("contents = " + tmpStr);
if ((!isDigitalclock) &&
(!tmpStr.isEmpty())) {
mText.setText(tmpStr);
}
}
}
partAttrList = partElmt.getElementsByTagName("font");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
tmpStr = partAttrElmnt.getAttribute("filename");
if (!tmpStr.isEmpty()) {
mText.setCustomFont(partAttrElmnt.getAttribute("filename"), Integer.parseInt(partAttrElmnt.getAttribute("size")));
}
tmpStr = partAttrElmnt.getAttribute("family");
if (!tmpStr.isEmpty())
{
NodeList bitmapFontsList = this.doc.getElementsByTagName("bitmap-fonts");
if (bitmapFontsList.getLength() != 0)
{
Node bitmapFontsNode = bitmapFontsList.item(0);
NodeList bitmapFontList = bitmapFontsNode.getChildNodes();
for (int item = 0; item < bitmapFontList.getLength(); item++)
{
Node bitmapFontNode = bitmapFontList.item(item);
if (bitmapFontNode.getNodeType() == 1)
{
Element fontElmt = (Element)bitmapFontNode;
String fontName = fontElmt.getAttribute("name");
if (fontName.equals(tmpStr))
{
processBitmapFonts((Element)bitmapFontNode, mText);
break;
}
}
}
}
}
tmpStr = partAttrElmnt.getAttribute("slant");
if ((!tmpStr.isEmpty()) &&
(tmpStr.equals("italic"))) {
mText.addFontStyle(2);
}
tmpStr = partAttrElmnt.getAttribute("weight");
if ((!tmpStr.isEmpty()) &&
(tmpStr.equals("bold"))) {
mText.addFontStyle(1);
}
}
partAttrList = partElmt.getElementsByTagName("rotation");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
String source = partAttrElmnt.getAttribute("source");
if (!source.isEmpty()) {
mText.setSource(Source.findById(source));
} else if (!partAttrElmnt.getAttribute("angle").isEmpty()) {
if (Util.checkExprTag(partAttrElmnt.getAttribute("angle"))) {
mText.setAngle(Util.removeExprTag(partAttrElmnt.getAttribute("angle")));
} else {
mText.setAngle(Double.parseDouble(partAttrElmnt.getAttribute("angle")));
}
}
}
partAttrList = partElmt.getElementsByTagName("underline");
if (partAttrList.getLength() != 0) {
mText.addFontStyle(4);
}
partAttrList = partElmt.getElementsByTagName("strike-through");
if (partAttrList.getLength() != 0) {
mText.addFontStyle(8);
}
mText.setFontStyle(mText.getFontStyle());
return mText;
}
ModelComponent processCondition(Element conditionElmt, ModelGroup group, int start, int end, ModelComponent _obj, ActionConfig actionConf)
{
ModelComponent conditionObj = _obj;
int depth = 0;
int startValue = 0;
String source = conditionElmt.getAttribute("source");
if (source.equals("battery.percent"))
{
NodeList conditionChildList = conditionElmt.getChildNodes();
for (int i = 0; i < conditionChildList.getLength(); i++)
{
Node conditionChildNode = conditionChildList.item(i);
if (conditionChildNode.getNodeType() == 1)
{
Element conditionChildElmnt = (Element)conditionChildNode;
if (conditionChildNode.getNodeName().equals("compare"))
{
String compareValue = conditionChildElmnt.getAttribute("lt");
if (compareValue.isEmpty()) {
compareValue = conditionChildElmnt.getAttribute("le");
}
int value = Integer.parseInt(compareValue);
ModelComponent obj = processCompareBattery(conditionChildElmnt, group, start + startValue, value, conditionObj, actionConf);
if ((obj != null) && (conditionObj == null)) {
conditionObj = obj;
} else {
startValue = value;
}
}
else
{
conditionChildNode.getNodeName().equals("default");
}
}
}
}
else if (source.equals("pedometer.stepPercent"))
{
NodeList conditionChildList = conditionElmt.getChildNodes();
for (int i = 0; i < conditionChildList.getLength(); i++)
{
Node conditionChildNode = conditionChildList.item(i);
if (conditionChildNode.getNodeType() == 1)
{
Element conditionChildElmnt = (Element)conditionChildNode;
if (conditionChildNode.getNodeName().equals("compare"))
{
String compareValue = conditionChildElmnt.getAttribute("lt");
if (compareValue.isEmpty()) {
compareValue = conditionChildElmnt.getAttribute("le");
}
if (!compareValue.isEmpty())
{
int value = Integer.parseInt(compareValue);
ModelComponent obj = processComparePedometer(conditionChildElmnt, group, start + startValue, value, conditionObj, actionConf);
if ((obj != null) && (conditionObj == null)) {
conditionObj = obj;
} else {
startValue = value;
}
}
}
else
{
conditionChildNode.getNodeName().equals("default");
}
}
}
}
else
{
if (source.equals("hour0-23.minute"))
{
depth = 1;
}
else if (source.equals("second.millisecond"))
{
depth = 2;
startValue = start;
}
NodeList conditionChildList = conditionElmt.getChildNodes();
for (int i = 0; i < conditionChildList.getLength(); i++)
{
Node conditionChildNode = conditionChildList.item(i);
if (conditionChildNode.getNodeType() == 1)
{
Element conditionChildElmnt = (Element)conditionChildNode;
if (conditionChildNode.getNodeName().equals("compare"))
{
String compareValue = conditionChildElmnt.getAttribute("lt");
if (!compareValue.isEmpty()) {
if (depth == 1)
{
int value = (int)Math.round((Double.parseDouble(compareValue) + 0.005D) * 54000.0D);
if (value % 900 != 0) {
value = (int)Math.round(Double.parseDouble(compareValue) * 54000.0D);
}
ModelComponent obj = processCompareTimeline(conditionChildElmnt, group, start + startValue, value, conditionObj, actionConf);
if ((obj != null) && (conditionObj == null)) {
conditionObj = obj;
} else {
startValue = value;
}
}
else
{
int value = (int)Math.round(Double.parseDouble(compareValue) * 15.0D) + start;
ModelComponent obj = processCompareTimeline(conditionChildElmnt, group, startValue, value, conditionObj, actionConf);
if ((obj != null) && (conditionObj == null)) {
conditionObj = obj;
} else {
startValue = value;
}
}
}
}
else if ((conditionChildNode.getNodeName().equals("default")) &&
(depth == 2))
{
ModelComponent obj = processCompareTimeline(conditionChildElmnt, group, startValue, end, conditionObj, actionConf);
if ((obj != null) && (conditionObj == null)) {
conditionObj = obj;
} else {
startValue = end;
}
}
}
}
}
return conditionObj;
}
ModelComponent processCompareTimeline(Element compareElmt, ModelGroup group, int start, int end, ModelComponent _obj, ActionConfig actionConf)
{
ModelComponent conditionObj = _obj;
int startValue = start;
int endValue = end;
NodeList compareChildList = compareElmt.getChildNodes();
if (compareChildList.getLength() == 0) {
return null;
}
for (int i = 0; i < compareChildList.getLength(); i++)
{
Node compareChildNode = compareChildList.item(i);
if (compareChildNode.getNodeType() == 1)
{
Element compareChildElmnt = (Element)compareChildNode;
if (compareChildNode.getNodeName().equals("part"))
{
ModelComponent obj = processPart(compareChildElmnt, group, actionConf);
if (obj != null)
{
endValue = end;
if (_obj == null)
{
conditionObj = obj;
conditionObj.getCondition().deleteAll();
conditionObj.getCondition().addItem(startValue, endValue);
}
else
{
conditionObj.getCondition().addItem(startValue, endValue);
}
}
else
{
startValue = end;
}
return obj;
}
if (compareChildNode.getNodeName().equals("condition"))
{
ModelComponent obj = processCondition(compareChildElmnt, group, endValue - 900, endValue, conditionObj, actionConf);
return obj;
}
}
}
return null;
}
ModelComponent processCompareBattery(Element compareElmt, ModelGroup group, int start, int end, ModelComponent _obj, ActionConfig actionConf)
{
ModelComponent conditionObj = _obj;
int startValue = start;
int endValue = end;
NodeList compareChildList = compareElmt.getChildNodes();
if (compareChildList.getLength() == 0) {
return null;
}
for (int i = 0; i < compareChildList.getLength(); i++)
{
Node compareChildNode = compareChildList.item(i);
if (compareChildNode.getNodeType() == 1)
{
Element compareChildElmnt = (Element)compareChildNode;
if (compareChildNode.getNodeName().equals("part"))
{
ModelComponent obj = processPart(compareChildElmnt, group, actionConf);
if (obj != null)
{
endValue = end;
if (conditionObj == null)
{
conditionObj = obj;
conditionObj.getCondition().setSource("battery");
conditionObj.getCondition().deleteAll();
conditionObj.getCondition().addItem(startValue, endValue);
}
else
{
conditionObj.getCondition().addItem(startValue, endValue);
}
}
else
{
startValue = end;
}
return conditionObj;
}
}
}
return null;
}
void processBitmapFonts(Element bitmapElmt, ModelText txt)
{
NodeList bitmapChildList = bitmapElmt.getChildNodes();
if (bitmapChildList.getLength() == 0) {
return;
}
txt.loadBitmapFont(bitmapElmt.getAttribute("name"));
for (int item = 0; item < bitmapChildList.getLength(); item++)
{
Node bitmapChildNode = bitmapChildList.item(item);
if (bitmapChildNode.getNodeType() == 1)
{
Element bitmapChildElmnt = (Element)bitmapChildNode;
if (bitmapChildNode.getNodeName().equals("character"))
{
String name = bitmapChildElmnt.getAttribute("name");
txt.getBitmapFont().setCharacter(name,
RM.getImage(this.projectDir + BuildConfig.PATH_CUSTOM_FONT + name + '/' + bitmapChildElmnt.getAttribute("filepath")));
}
}
}
}
ModelComponent processComparePedometer(Element compareElmt, ModelGroup group, int start, int end, ModelComponent _obj, ActionConfig actionConf)
{
ModelComponent conditionObj = _obj;
int startValue = start;
int endValue = end;
NodeList compareChildList = compareElmt.getChildNodes();
if (compareChildList.getLength() == 0) {
return null;
}
for (int i = 0; i < compareChildList.getLength(); i++)
{
Node compareChildNode = compareChildList.item(i);
if (compareChildNode.getNodeType() == 1)
{
Element compareChildElmnt = (Element)compareChildNode;
if (compareChildNode.getNodeName().equals("part"))
{
ModelComponent obj = processPart(compareChildElmnt, group, actionConf);
if (obj != null)
{
endValue = end;
if (conditionObj == null)
{
conditionObj = obj;
conditionObj.getCondition().setSource("workout");
conditionObj.getCondition().deleteAll();
conditionObj.getCondition().addItem(startValue, endValue);
}
else
{
conditionObj.getCondition().addItem(startValue, endValue);
}
}
else
{
startValue = end;
}
return conditionObj;
}
}
}
return null;
}
public int getWidth()
{
return this.width;
}
public int getHeight()
{
return this.height;
}
}
Why such complicated? just download the gwd file and convert to tpk file to upload to your smartwatch. I can teach you how to do if you interest to know it. Ping me at [email protected]
Zeuserx said:
This is from the GWD file : C:\Program Files (x86)\GearWatchDesigner\plugins\com.samsung.gwd_1.6.2.201810300802.jar
This is a Java package. When looking inside with a "Java decompiler" (free download), find the loadXml.class and you'll see the following code. Once we analyze this, I think we can kind of figure out the schema.
Code:
package com.samsung.gwd;
import com.samsung.gwd.gef.models.ActionConfig;
import com.samsung.gwd.gef.models.ActionConfigEnum.ACTION_STATE;
import com.samsung.gwd.gef.models.Condition;
import com.samsung.gwd.gef.models.ModelAnimation;
import com.samsung.gwd.gef.models.ModelBackground;
import com.samsung.gwd.gef.models.ModelComponent;
import com.samsung.gwd.gef.models.ModelDigitalclock;
import com.samsung.gwd.gef.models.ModelGroup;
import com.samsung.gwd.gef.models.ModelHand;
import com.samsung.gwd.gef.models.ModelImage;
import com.samsung.gwd.gef.models.ModelIndex;
import com.samsung.gwd.gef.models.ModelRoot;
import com.samsung.gwd.gef.models.ModelText;
import com.samsung.gwd.source.Source;
import com.samsung.gwd.ui.dialog.bitmapfont.BitmapFont;
import com.samsung.gwd.utils.RM;
import com.samsung.gwd.utils.Util;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
public class LoadXml
{
public static final int TIME_ONE_MINUTE = 900;
public static final int TIME_ONE_HOUR = 54000;
public static final double PLATFORM_HOUR_MINUTE_CORRECTION = 0.005D;
Project project;
ModelRoot root;
String path;
Document doc;
String projectDir;
int width;
int height;
public LoadXml(String path, String name, Project project)
{
this.path = path;
File file = new File(path + name);
this.project = project;
this.projectDir = project.getProjectDir();
if (file.isFile())
{
DocumentBuilderFactory docBuildFact = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder docBuild = docBuildFact.newDocumentBuilder();
this.doc = docBuild.parse(file);
this.doc.getDocumentElement().normalize();
NodeList watchface = this.doc.getElementsByTagName("watchface");
Node watchfaceNode = watchface.item(0);
this.width = Integer.parseInt(((Element)watchfaceNode).getAttribute("width"));
this.height = Integer.parseInt(((Element)watchfaceNode).getAttribute("height"));
NodeList groupsList = this.doc.getElementsByTagName("groups");
for (int i = 0; i < groupsList.getLength(); i++)
{
Node groupsNode = groupsList.item(i);
processGroups((Element)groupsNode);
}
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
Application.LOGGER.error("Loading XML failed : " + path + name);
}
}
void processGroups(Element groupsElmt)
{
if (groupsElmt.getAttribute("type").equals("ambient"))
{
this.project.initLowBitAmbientMode();
this.root = this.project.getAmbientLowRoot();
}
else if (groupsElmt.getAttribute("type").equals("ambient-fullcolor"))
{
this.project.initHighColorAmbientMode();
this.root = this.project.getAmbientHighRoot();
}
else if (groupsElmt.getAttribute("type").equals("current"))
{
this.root = this.project.getModelRoot();
}
else
{
this.root = this.project.getNormalRoot();
}
NodeList groupList = groupsElmt.getElementsByTagName("group");
for (int j = 0; j < groupList.getLength(); j++)
{
Node groupNode = groupList.item(j);
processGroup((Element)groupNode);
}
}
void processGroup(Element groupElm)
{
ModelGroup group = null;
ActionConfig actionConf = null;
String tmpStr = groupElm.getAttribute("x");
if (!groupElm.getAttribute("name").startsWith("__DEFAULT_GROUP")) {
if (!tmpStr.isEmpty())
{
group = new ModelGroup(this.root);
group.setRect(Integer.parseInt(groupElm.getAttribute("x")), Integer.parseInt(groupElm.getAttribute("y")),
Integer.parseInt(groupElm.getAttribute("width")), Integer.parseInt(groupElm.getAttribute("height")));
}
else
{
group = new ModelGroup(this.root);
group.setRect(0, 0, this.width, this.height);
}
}
Point groupLoc;
Point groupLoc;
if (!groupElm.getAttribute("x").isEmpty()) {
groupLoc = new Point(Integer.parseInt(groupElm.getAttribute("x")), Integer.parseInt(groupElm.getAttribute("y")));
} else {
groupLoc = new Point(0, 0);
}
NodeList groupChildList = groupElm.getChildNodes();
for (int i = 0; i < groupChildList.getLength(); i++)
{
Node childNode = groupChildList.item(i);
if ((childNode.getNodeType() == 1) && (childNode.getNodeName().equals("action")))
{
Element childElm = (Element)childNode;
String on_event = childElm.getAttribute("on_event");
if (on_event.equals("tap"))
{
String type = childElm.getAttribute("type");
if (type.equals("launch"))
{
NodeList launchList = childElm.getElementsByTagName("launch");
if (launchList.getLength() != 0)
{
Node launchNode = launchList.item(0);
String appid = ((Element)launchNode).getAttribute("app_id");
if (appid.isEmpty()) {
appid = ((Element)launchNode).getAttribute("preset");
}
if (actionConf != null) {
break;
}
actionConf = new ActionConfig(DeviceSpec.GEAR_S2.getOpenAppTable());
actionConf.setActionState("Open App");
actionConf.setSelectAppId(appid);
}
}
else if (type.equals("image-set-show-next"))
{
if (actionConf != null) {
break;
}
actionConf = new ActionConfig(DeviceSpec.GEAR_S2.getOpenAppTable());
actionConf.setActionState("Change Image");
}
}
}
}
for (int i = 0; i < groupChildList.getLength(); i++)
{
Node childNode = groupChildList.item(i);
if (childNode.getNodeType() == 1)
{
Element childElmnt = (Element)childNode;
if (childNode.getNodeName().equals("part"))
{
ModelComponent model = processPart(childElmnt, group, actionConf);
if (model != null)
{
model.setLocation(model.getLocation().x + groupLoc.x, model.getLocation().y + groupLoc.y);
try
{
if (actionConf == null) {
break;
}
actionConf.setModel(model);
model.setActionConfig(actionConf);
model.setButton(true);
}
catch (Exception e)
{
e.printStackTrace();
if (group == null)
{
this.root.removeChild(model); continue;
}
group.removeChild(model);
continue;
}
}
}
else if (childNode.getNodeName().equals("condition"))
{
ModelComponent model = processCondition(childElmnt, group, 0, 0, null, actionConf);
if (model != null)
{
model.setLocation(model.getLocation().x + groupLoc.x, model.getLocation().y + groupLoc.y);
try
{
if (group == null) {
this.root.addChild(model);
} else {
group.addChild(model);
}
if (actionConf == null) {
break;
}
actionConf.setModel(model);
model.setActionConfig(actionConf);
model.setButton(true);
}
catch (Exception e)
{
e.printStackTrace();
if (group == null) {
this.root.removeChild(model);
} else {
group.removeChild(model);
}
}
}
}
}
}
}
ModelComponent processPart(Element partElmt, ModelGroup group, ActionConfig actionConf)
{
Rectangle partRect = null;
String tmpStr = partElmt.getAttribute("x");
if (!tmpStr.isEmpty()) {
partRect = new Rectangle(Integer.parseInt(tmpStr),
Integer.parseInt(partElmt.getAttribute("y")),
Integer.parseInt(partElmt.getAttribute("width")),
Integer.parseInt(partElmt.getAttribute("height")));
}
String type = partElmt.getAttribute("type");
if (type.equals("image")) {
return processPartImage(partElmt, group, partRect, actionConf);
}
if (type.equals("text")) {
return processPartText(partElmt, group, partRect);
}
if (!type.equals("draw")) {
Application.LOGGER.error("Not supporeted part type : " + type);
}
return null;
}
ModelComponent processPartImage(Element partElmt, ModelGroup group, Rectangle partRect, ActionConfig actionConf)
{
ModelImage obj = null;
boolean isHands = false;
boolean isBackground = false;
boolean isIndex = false;
ModelComponent parent;
ModelComponent parent;
if (group != null) {
parent = group;
} else {
parent = this.root;
}
NodeList partAttrList = null;
Node partAttrNode = null;
Element partAttrElmnt = null;
Element metaElmnt = null;
partAttrList = partElmt.getElementsByTagName("metadata");
if (partAttrList.getLength() != 0)
{
for (int i = 0; i < partAttrList.getLength(); i++)
{
partAttrNode = partAttrList.item(i);
metaElmnt = (Element)partAttrNode;
String tmpStr = metaElmnt.getAttribute("type");
if (tmpStr.equals("hands")) {
isHands = true;
} else if (tmpStr.equals("background")) {
isBackground = true;
} else if (tmpStr.equals("index")) {
isIndex = true;
}
}
}
else
{
partAttrList = partElmt.getElementsByTagName("rotation");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
if ((partAttrElmnt.getAttribute("source").equals("hour0-23.minute")) ||
(partAttrElmnt.getAttribute("source").equals("minute"))) {
isHands = true;
}
}
}
partAttrList = partElmt.getElementsByTagName("image-set");
if ((partAttrList.getLength() == 0) || ((actionConf != null) && (actionConf.getActionState() == ActionConfigEnum.ACTION_STATE.CHANGE_IMAGE)))
{
String baseName = null;
if ((actionConf != null) && (actionConf.getActionState() == ActionConfigEnum.ACTION_STATE.CHANGE_IMAGE))
{
String projResDir = new String(this.project.getProjectDir() + BuildConfig.PATH_XML);
partAttrList = partElmt.getElementsByTagName("image-set");
if (partAttrList.getLength() != 0)
{
int changeNum = 0;
NodeList imageSetChildList = partAttrList.item(0).getChildNodes();
for (int nodeIndex = 0; nodeIndex < imageSetChildList.getLength(); nodeIndex++)
{
Node imageSetChildNode = imageSetChildList.item(nodeIndex);
if (imageSetChildNode.getNodeType() == 1) {
if (imageSetChildNode.getNodeName().equals("image"))
{
Element imageElmnt = (Element)imageSetChildNode;
if (nodeIndex == 0)
{
baseName = imageElmnt.getTextContent();
}
else
{
if ((imageElmnt.getTextContent() == "") || (imageElmnt.getTextContent().compareTo(baseName) == 0))
{
actionConf.setChangeImage(null, changeNum, null);
}
else
{
String str_des = new String(imageElmnt.getTextContent());
if (System.getProperty("os.name").contains("Windows")) {
while (str_des.contains("/")) {
str_des = str_des.replace("/", File.separator);
}
}
actionConf.setChangeImage(RM.getImage(projResDir + str_des),
changeNum, projResDir + str_des);
}
changeNum++;
}
}
}
}
}
Rectangle tempRect = new Rectangle(partRect);
if (isHands) {
obj = new ModelHand(parent, this.path, baseName);
} else if (isBackground) {
obj = new ModelBackground(parent, this.path, baseName);
} else {
obj = new ModelImage(parent, this.path, baseName);
}
obj.setRect(tempRect);
}
else
{
partAttrList = partElmt.getElementsByTagName("image");
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
NodeList partAttrChildList = partAttrNode.getChildNodes();
Rectangle tempRect = new Rectangle(partRect);
if (partAttrChildList.getLength() == 1)
{
if (isHands)
{
obj = new ModelHand(parent, this.path, partAttrElmnt.getTextContent());
obj.setRect(tempRect);
}
else if (isBackground)
{
obj = new ModelBackground(parent, this.path, partAttrElmnt.getTextContent());
obj.setRect(tempRect);
}
else if (isIndex)
{
String tmpStr = metaElmnt.getAttribute("image");
if (!tmpStr.isEmpty())
{
obj = new ModelIndex(parent, this.path, tmpStr);
obj.setRect(tempRect);
((ModelIndex)obj).setOriginalRect(new Rectangle(Integer.parseInt(metaElmnt.getAttribute("x")),
Integer.parseInt(metaElmnt.getAttribute("y")),
Integer.parseInt(metaElmnt.getAttribute("width")),
Integer.parseInt(metaElmnt.getAttribute("height"))));
}
else
{
obj = new ModelIndex(parent, this.path, partAttrElmnt.getTextContent());
obj.setRect(tempRect);
}
tmpStr = metaElmnt.getAttribute("range");
if (tmpStr.isEmpty()) {
return null;
}
((ModelIndex)obj).setRange(0.0D, Integer.parseInt(tmpStr));
tmpStr = metaElmnt.getAttribute("number");
((ModelIndex)obj).setNumber(Integer.parseInt(tmpStr));
((ModelIndex)obj).apply();
((ModelIndex)obj).setRect(tempRect);
}
else
{
obj = new ModelImage(parent, this.path, partAttrElmnt.getTextContent());
obj.setRect(tempRect);
}
}
else {
Application.LOGGER.error("LoadXml : Implement me - image condition, length=" + partAttrChildList.getLength());
}
}
if (obj != null)
{
partAttrList = partElmt.getElementsByTagName("color");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
String tmpStr = partAttrElmnt.getAttribute("a");
if (!tmpStr.isEmpty())
{
tmpStr = partAttrElmnt.getAttribute("r");
if (!tmpStr.isEmpty())
{
obj.setFilterEnable(true);
float[] hsl = Color.RGBtoHSB(Integer.parseInt(partAttrElmnt.getAttribute("r")),
Integer.parseInt(partAttrElmnt.getAttribute("g")),
Integer.parseInt(partAttrElmnt.getAttribute("b")), null);
obj.setHue((int)(hsl[0] * 360.0F - 180.0F));
obj.setSaturation((int)(hsl[1] * 200.0F - 100.0F));
obj.setLightness((int)(hsl[2] * 200.0F - 100.0F));
obj.setAlpha(Integer.parseInt(partAttrElmnt.getAttribute("a")));
}
else
{
obj.setAlpha(Integer.parseInt(partAttrElmnt.getAttribute("a")));
}
}
}
partAttrList = partElmt.getElementsByTagName("rotation");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
String source = partAttrElmnt.getAttribute("source");
if (!source.isEmpty())
{
if (isHands)
{
ModelHand hand = (ModelHand)obj;
hand.setSource(Source.findById(source));
if (!partElmt.getAttribute("x").isEmpty())
{
hand.setPivot(Integer.parseInt(partAttrElmnt.getAttribute("center_x")) +
Integer.parseInt(partElmt.getAttribute("x")),
Integer.parseInt(partAttrElmnt.getAttribute("center_y")) +
Integer.parseInt(partElmt.getAttribute("y")));
hand.setStartAngle(Double.parseDouble(partAttrElmnt.getAttribute("start_angle")));
hand.setEndAngle(Double.parseDouble(partAttrElmnt.getAttribute("end_angle")));
hand.setStartValue(Double.parseDouble(partAttrElmnt.getAttribute("start_value")));
hand.setEndValue(Double.parseDouble(partAttrElmnt.getAttribute("end_value")));
}
else
{
if (group == null) {
hand.setPivot(Integer.parseInt(partAttrElmnt.getAttribute("center_x")),
Integer.parseInt(partAttrElmnt.getAttribute("center_y")));
}
hand.setStartAngle(Double.parseDouble(partAttrElmnt.getAttribute("start_angle")));
hand.setEndAngle(Double.parseDouble(partAttrElmnt.getAttribute("end_angle")));
hand.setStartValue(Double.parseDouble(partAttrElmnt.getAttribute("start_value")));
hand.setEndValue(Double.parseDouble(partAttrElmnt.getAttribute("end_value")));
}
if (partAttrElmnt.getAttribute("animation").equals("tick"))
{
hand.setTensionFrame(Integer.parseInt(partAttrElmnt.getAttribute("tick_frame")) / 2);
hand.setTensionAngle(Double.parseDouble(partAttrElmnt.getAttribute("tick_angle")));
hand.setTension((int)(hand.getTensionAngle() * 100.0D / 6.0D));
hand.setTensionEnabled(true);
}
if (source.equals("hour0-11.minute"))
{
hand.setSource(Source.findById("hour0-23.minute"));
if (hand.getStartAngle() < hand.getEndAngle()) {
hand.setEndAngle(hand.getEndAngle() + 360.0D);
} else {
hand.setEndAngle(hand.getEndAngle() - 360.0D);
}
}
}
}
else if (!partAttrElmnt.getAttribute("angle").isEmpty()) {
if (Util.checkExprTag(partAttrElmnt.getAttribute("angle"))) {
obj.setAngle(Util.removeExprTag(partAttrElmnt.getAttribute("angle")));
} else {
obj.setAngle(Double.parseDouble(partAttrElmnt.getAttribute("angle")));
}
}
}
}
}
else
{
partAttrList = partElmt.getElementsByTagName("image-set");
if (partAttrList.getLength() != 0)
{
ModelAnimation ani = new ModelAnimation(parent);
int frameNum = 0;
ani.setRect(partRect);
NodeList imageSetChildList = partAttrList.item(0).getChildNodes();
for (int nodeIndex = 0; nodeIndex < imageSetChildList.getLength(); nodeIndex++)
{
Node imageSetChildNode = imageSetChildList.item(nodeIndex);
if (imageSetChildNode.getNodeType() == 1)
{
if (imageSetChildNode.getNodeName().equals("image"))
{
Element imageElmnt = (Element)imageSetChildNode;
ModelImage frameItem = new ModelImage(ani, this.path, imageElmnt.getTextContent());
frameItem.setRect(0, 0, partRect.width, partRect.height);
frameItem.setId("Frame " + (nodeIndex + 1));
frameItem.getCondition().deleteAll();
frameItem.getCondition().addItem(frameNum, frameNum + 1);
}
frameNum++;
}
}
partAttrList = partElmt.getElementsByTagName("color");
if (partAttrList.getLength() != 0)
{
partAttrNode = partAttrList.item(0);
partAttrElmnt = (Element)partAttrNode;
String tmpStr = partAttrElmnt.getAttribute("a");
if (!tmpStr.isEmpty()) {
ani.setAlpha(Integer.parseInt(partAttrElmnt.getAttribute("a")));
}
}
partAttrList = partElmt.getElementsByTagName("rotation");
if (partAttrList.getLength() != 0)
{
partAttrElmnt = (Element)partAttrList.item(0);
if (!partAttrElmnt.getAttribute("angle").isEmpty()) {
if (Util.checkExprTag(partAttrElmnt.getAttribute("angle"))) {
ani.setAngle(Util.removeExprTag(partAttrElmnt.getAttribute("angle")));
} else {
ani.setAngle(Double.parseDouble(partAttrElmnt.getAttribute("angle")));
}
}
}
return ani;
}
}
return obj;
}
Click to expand...
Click to collapse

Categories

Resources