FlatCAMApp.py 418 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import tkinter as tk
  20. from PyQt5 import QtPrintSupport
  21. from contextlib import contextmanager
  22. import gc
  23. from xml.dom.minidom import parseString as parse_xml_string
  24. # #######################################
  25. # # Imports part of FlatCAM ##
  26. # #######################################
  27. from ObjectCollection import *
  28. from FlatCAMObj import *
  29. from flatcamGUI.PlotCanvas import *
  30. from flatcamGUI.FlatCAMGUI import *
  31. from FlatCAMCommon import LoudDict
  32. from FlatCAMPostProc import load_postprocessors
  33. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  34. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  35. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  36. from FlatCAMProcess import *
  37. from FlatCAMWorkerStack import WorkerStack
  38. from flatcamGUI.VisPyVisuals import Color
  39. from vispy.gloo.util import _screenshot
  40. from vispy.io import write_png
  41. from flatcamTools import *
  42. from multiprocessing import Pool
  43. import tclCommands
  44. import gettext
  45. import FlatCAMTranslation as fcTranslate
  46. import builtins
  47. fcTranslate.apply_language('strings')
  48. if '_' not in builtins.__dict__:
  49. _ = gettext.gettext
  50. # ########################################
  51. # # App ###
  52. # ########################################
  53. class App(QtCore.QObject):
  54. """
  55. The main application class. The constructor starts the GUI.
  56. """
  57. # Get Cmd Line Options
  58. cmd_line_shellfile = ''
  59. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  60. try:
  61. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  62. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  63. except getopt.GetoptError:
  64. print(cmd_line_help)
  65. sys.exit(2)
  66. for opt, arg in cmd_line_options:
  67. if opt == '-h':
  68. print(cmd_line_help)
  69. sys.exit()
  70. elif opt == '--shellfile':
  71. cmd_line_shellfile = arg
  72. # ## Logging ###
  73. log = logging.getLogger('base')
  74. log.setLevel(logging.DEBUG)
  75. # log.setLevel(logging.WARNING)
  76. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  77. handler = logging.StreamHandler()
  78. handler.setFormatter(formatter)
  79. log.addHandler(handler)
  80. # ####################################
  81. # Version and VERSION DATE ###########
  82. # ####################################
  83. version = 8.97
  84. version_date = "2019/08/31"
  85. beta = True
  86. # current date now
  87. date = str(datetime.today()).rpartition('.')[0]
  88. date = ''.join(c for c in date if c not in ':-')
  89. date = date.replace(' ', '_')
  90. # URL for update checks and statistics
  91. version_url = "http://flatcam.org/version"
  92. # App URL
  93. app_url = "http://flatcam.org"
  94. # Manual URL
  95. manual_url = "http://flatcam.org/manual/index.html"
  96. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  97. # this variable will hold the project status
  98. # if True it will mean that the project was modified and not saved
  99. should_we_save = False
  100. # flag is True if saving action has been triggered
  101. save_in_progress = False
  102. # #################
  103. # # Signals ##
  104. # #################
  105. # Inform the user
  106. # Handled by:
  107. # * App.info() --> Print on the status bar
  108. inform = QtCore.pyqtSignal(str)
  109. app_quit = QtCore.pyqtSignal()
  110. # General purpose background task
  111. worker_task = QtCore.pyqtSignal(dict)
  112. # File opened
  113. # Handled by:
  114. # * register_folder()
  115. # * register_recent()
  116. # Note: Setting the parameters to unicode does not seem
  117. # to have an effect. Then are received as Qstring
  118. # anyway.
  119. # File type and filename
  120. file_opened = QtCore.pyqtSignal(str, str)
  121. # File type and filename
  122. file_saved = QtCore.pyqtSignal(str, str)
  123. # Percentage of progress
  124. progress = QtCore.pyqtSignal(int)
  125. plots_updated = QtCore.pyqtSignal()
  126. # Emitted by new_object() and passes the new object as argument, plot flag.
  127. # on_object_created() adds the object to the collection, plots on appropriate flag
  128. # and emits new_object_available.
  129. object_created = QtCore.pyqtSignal(object, bool, bool)
  130. # Emitted when a object has been changed (like scaled, mirrored)
  131. object_changed = QtCore.pyqtSignal(object)
  132. # Emitted after object has been plotted.
  133. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  134. object_plotted = QtCore.pyqtSignal(object)
  135. # Emitted when a new object has been added or deleted from/to the collection
  136. object_status_changed = QtCore.pyqtSignal(object, str)
  137. message = QtCore.pyqtSignal(str, str, str)
  138. # Emmited when shell command is finished(one command only)
  139. shell_command_finished = QtCore.pyqtSignal(object)
  140. # Emitted when multiprocess pool has been recreated
  141. pool_recreated = QtCore.pyqtSignal(object)
  142. # Emitted when an unhandled exception happens
  143. # in the worker task.
  144. thread_exception = QtCore.pyqtSignal(object)
  145. # used to signal that there are arguments for the app
  146. args_at_startup = QtCore.pyqtSignal()
  147. def __init__(self, user_defaults=True, post_gui=None):
  148. """
  149. Starts the application.
  150. :return: app
  151. :rtype: App
  152. """
  153. App.log.info("FlatCAM Starting...")
  154. self.main_thread = QtWidgets.QApplication.instance().thread()
  155. # #######################
  156. # # ## OS-specific ######
  157. # #######################
  158. portable = False
  159. # Folder for user settings.
  160. if sys.platform == 'win32':
  161. from win32com.shell import shell, shellcon
  162. if platform.architecture()[0] == '32bit':
  163. App.log.debug("Win32!")
  164. else:
  165. App.log.debug("Win64!")
  166. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  167. try:
  168. with open(config_file, 'r') as f:
  169. try:
  170. for line in f:
  171. param = str(line).rpartition('=')
  172. if param[0] == 'portable':
  173. try:
  174. portable = eval(param[2])
  175. except NameError:
  176. portable = False
  177. except Exception as e:
  178. log.debug('App.__init__() -->%s' % str(e))
  179. return
  180. except FileNotFoundError:
  181. pass
  182. if portable is False:
  183. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  184. else:
  185. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  186. self.os = 'windows'
  187. else: # Linux/Unix/MacOS
  188. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  189. self.os = 'unix'
  190. # ############################ ##
  191. # # ## Setup folders and files # ##
  192. # ############################ ##
  193. if not os.path.exists(self.data_path):
  194. os.makedirs(self.data_path)
  195. App.log.debug('Created data folder: ' + self.data_path)
  196. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  197. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  198. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  199. if not os.path.exists(self.postprocessorpaths):
  200. os.makedirs(self.postprocessorpaths)
  201. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  202. # create current_defaults.FlatConfig file if there is none
  203. try:
  204. f = open(self.data_path + '/current_defaults.FlatConfig')
  205. f.close()
  206. except IOError:
  207. App.log.debug('Creating empty current_defaults.FlatConfig')
  208. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  209. json.dump({}, f)
  210. f.close()
  211. # create factory_defaults.FlatConfig file if there is none
  212. try:
  213. f = open(self.data_path + '/factory_defaults.FlatConfig')
  214. f.close()
  215. except IOError:
  216. App.log.debug('Creating empty factory_defaults.FlatConfig')
  217. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  218. json.dump({}, f)
  219. f.close()
  220. try:
  221. f = open(self.data_path + '/recent.json')
  222. f.close()
  223. except IOError:
  224. App.log.debug('Creating empty recent.json')
  225. f = open(self.data_path + '/recent.json', 'w')
  226. json.dump([], f)
  227. f.close()
  228. try:
  229. fp = open(self.data_path + '/recent_projects.json')
  230. fp.close()
  231. except IOError:
  232. App.log.debug('Creating empty recent_projects.json')
  233. fp = open(self.data_path + '/recent_projects.json', 'w')
  234. json.dump([], fp)
  235. fp.close()
  236. # Application directory. CHDIR to it. Otherwise, trying to load
  237. # GUI icons will fail as their path is relative.
  238. # This will fail under cx_freeze ...
  239. self.app_home = os.path.dirname(os.path.realpath(__file__))
  240. App.log.debug("Application path is " + self.app_home)
  241. App.log.debug("Started in " + os.getcwd())
  242. # cx_freeze workaround
  243. if os.path.isfile(self.app_home):
  244. self.app_home = os.path.dirname(self.app_home)
  245. os.chdir(self.app_home)
  246. # Create multiprocessing pool
  247. self.pool = Pool()
  248. # variable to store mouse coordinates
  249. self.mouse = [0, 0]
  250. # ###################
  251. # # Initialize GUI ##
  252. # ###################
  253. # FlatCAM colors used in plotting
  254. self.FC_light_green = '#BBF268BF'
  255. self.FC_dark_green = '#006E20BF'
  256. self.FC_light_blue = '#a5a5ffbf'
  257. self.FC_dark_blue = '#0000ffbf'
  258. QtCore.QObject.__init__(self)
  259. self.ui = FlatCAMGUI(self.version, self.beta, self)
  260. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  261. self.ui.final_save.connect(self.final_save)
  262. # #############
  263. # ### Data ####
  264. # #############
  265. self.recent = []
  266. self.recent_projects = []
  267. self.clipboard = QtWidgets.QApplication.clipboard()
  268. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  269. self.project_filename = None
  270. self.toggle_units_ignore = False
  271. # self.defaults_form = PreferencesUI()
  272. # when adding entries here read the comments in the method found bellow named:
  273. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  274. self.defaults_form_fields = {
  275. # General App
  276. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  277. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  278. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  279. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  280. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  281. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  282. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  283. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  284. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  285. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  286. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  287. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  288. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  289. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  290. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  291. "global_delete_confirmation": self.ui.general_defaults_form.general_app_group.delete_conf_cb,
  292. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  293. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  294. # General GUI Preferences
  295. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  296. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  297. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  298. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  299. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  300. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  301. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  302. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  303. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  304. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  305. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  306. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  307. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  308. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  309. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  310. # General GUI Settings
  311. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  312. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  313. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  314. # Gerber General
  315. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  316. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  317. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  318. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  319. # Gerber Options
  320. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  321. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  322. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  323. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  324. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  325. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  326. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  327. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  328. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  329. # Gerber Advanced Options
  330. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  331. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  332. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  333. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  334. # Gerber Export
  335. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  336. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  337. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  338. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  339. # Gerber Editor
  340. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  341. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  342. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  343. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  344. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  345. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  346. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  347. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  348. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  349. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  350. "gerber_editor_circ_angle":
  351. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  352. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  353. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  354. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  355. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  356. # Excellon General
  357. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  358. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  359. "excellon_format_upper_in":
  360. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  361. "excellon_format_lower_in":
  362. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  363. "excellon_format_upper_mm":
  364. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  365. "excellon_format_lower_mm":
  366. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  367. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  368. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  369. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  370. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  371. # Excellon Options
  372. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  373. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  374. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  375. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  376. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  377. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  378. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  379. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  380. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  381. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  382. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  383. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  384. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  385. # Excellon Advanced Options
  386. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  387. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  388. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  389. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  390. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  391. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  392. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  393. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  394. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  395. # Excellon Export
  396. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  397. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  398. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  399. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  400. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  401. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  402. # Excellon Editor
  403. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  404. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  405. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  406. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  407. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  408. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  409. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  410. "excellon_editor_circ_angle":
  411. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  412. # Excellon Slots
  413. "excellon_editor_slot_direction":
  414. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  415. "excellon_editor_slot_angle":
  416. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  417. "excellon_editor_slot_length":
  418. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  419. # Excellon Slots
  420. "excellon_editor_slot_array_size":
  421. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  422. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  423. "excellon_editor_slot_lin_pitch":
  424. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  425. "excellon_editor_slot_lin_angle":
  426. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  427. "excellon_editor_slot_circ_dir":
  428. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  429. "excellon_editor_slot_circ_angle":
  430. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  431. # Geometry General
  432. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  433. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  434. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  435. # Geometry Options
  436. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  437. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  438. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  439. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  440. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  441. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  442. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  443. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  444. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  445. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  446. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  447. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  448. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  449. # Geometry Advanced Options
  450. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  451. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  452. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  453. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  454. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  455. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  456. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  457. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  458. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  459. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  460. # Geometry Editor
  461. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  462. # CNCJob General
  463. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  464. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  465. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  466. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontsize_sp,
  467. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry,
  468. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  469. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  470. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  471. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  472. # CNC Job Options
  473. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  474. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  475. # CNC Job Advanced Options
  476. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  477. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  478. # NCC Tool
  479. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  480. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  481. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  482. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  483. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  484. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  485. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  486. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  487. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  488. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  489. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  490. # CutOut Tool
  491. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  492. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  493. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  494. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  495. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  496. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  497. # Paint Area Tool
  498. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  499. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  500. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  501. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  502. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  503. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  504. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  505. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  506. # 2-sided Tool
  507. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  508. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  509. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  510. # Film Tool
  511. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  512. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  513. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  514. # Panelize Tool
  515. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  516. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  517. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  518. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  519. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  520. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  521. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  522. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  523. # Calculators Tool
  524. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  525. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  526. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  527. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  528. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  529. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  530. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  531. # Transformations Tool
  532. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  533. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  534. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  535. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  536. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  537. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  538. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  539. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  540. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  541. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  542. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  543. # SolderPaste Dispensing Tool
  544. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  545. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  546. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  547. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  548. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  549. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  550. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  551. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  552. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  553. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  554. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  555. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  556. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  557. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  558. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  559. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  560. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb
  561. }
  562. # ############################
  563. # ### LOAD POSTPROCESSORS ####
  564. # ############################
  565. self.postprocessors = load_postprocessors(self)
  566. for name in list(self.postprocessors.keys()):
  567. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  568. if name.partition('_')[0] == 'Paste':
  569. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  570. continue
  571. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  572. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  573. if name == 'hpgl':
  574. continue
  575. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  576. # ############################
  577. # ### LOAD LANGUAGES ####
  578. # ############################
  579. self.languages = fcTranslate.load_languages()
  580. for name in sorted(self.languages.values()):
  581. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  582. self.defaults = LoudDict()
  583. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  584. self.defaults.update({
  585. # Global APP Preferences
  586. "global_serial": 0,
  587. "global_stats": {},
  588. "global_tabs_detachable": True,
  589. "units": "IN",
  590. "global_app_level": 'b',
  591. "global_portable": False,
  592. "global_language": 'English',
  593. "global_version_check": True,
  594. "global_send_stats": True,
  595. "global_pan_button": '2',
  596. "global_mselect_key": 'Control',
  597. "global_project_at_startup": False,
  598. "global_project_autohide": True,
  599. "global_toggle_tooltips": True,
  600. "global_worker_number": 2,
  601. "global_tolerance": 0.01,
  602. "global_open_style": True,
  603. "global_delete_confirmation": True,
  604. "global_compression_level": 3,
  605. "global_save_compressed": True,
  606. # Global GUI Preferences
  607. "global_gridx": 0.0393701,
  608. "global_gridy": 0.0393701,
  609. "global_snap_max": 0.001968504,
  610. "global_workspace": False,
  611. "global_workspaceT": "A4P",
  612. "global_grid_context_menu": {
  613. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  614. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  615. },
  616. "global_plot_fill": '#BBF268BF',
  617. "global_plot_line": '#006E20BF',
  618. "global_sel_fill": '#a5a5ffbf',
  619. "global_sel_line": '#0000ffbf',
  620. "global_alt_sel_fill": '#BBF268BF',
  621. "global_alt_sel_line": '#006E20BF',
  622. "global_draw_color": '#FF0000',
  623. "global_sel_draw_color": '#0000FF',
  624. "global_proj_item_color": '#000000',
  625. "global_proj_item_dis_color": '#b7b7cb',
  626. "global_toolbar_view": 511,
  627. "global_background_timeout": 300000, # Default value is 5 minutes
  628. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  629. # (python trace only for unknown errors),
  630. # 1 = show trace(show trace always),
  631. # 2 = (For the future).
  632. # Persistence
  633. "global_last_folder": None,
  634. "global_last_save_folder": None,
  635. # Default window geometry
  636. "global_def_win_x": 100,
  637. "global_def_win_y": 100,
  638. "global_def_win_w": 1024,
  639. "global_def_win_h": 650,
  640. "global_def_notebook_width": 1,
  641. # Constants...
  642. "global_defaults_save_period_ms": 20000, # Time between default saves.
  643. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  644. "global_shell_at_startup": False, # Show the shell at startup.
  645. "global_recent_limit": 10, # Max. items in recent list.
  646. "fit_key": 'V',
  647. "zoom_out_key": '-',
  648. "zoom_in_key": '=',
  649. "grid_toggle_key": 'G',
  650. "global_zoom_ratio": 1.5,
  651. "global_point_clipboard_format": "(%.4f, %.4f)",
  652. "global_zdownrate": None,
  653. # General GUI Settings
  654. "global_hover": False,
  655. "global_selection_shape": True,
  656. "global_layout": "compact",
  657. # Gerber General
  658. "gerber_plot": True,
  659. "gerber_solid": True,
  660. "gerber_multicolored": False,
  661. "gerber_isotooldia": 0.00787402,
  662. "gerber_isopasses": 1,
  663. "gerber_isooverlap": 0.00393701,
  664. # Gerber Options
  665. "gerber_combine_passes": False,
  666. "gerber_milling_type": "cl",
  667. "gerber_noncoppermargin": 0.00393701,
  668. "gerber_noncopperrounded": False,
  669. "gerber_bboxmargin": 0.00393701,
  670. "gerber_bboxrounded": False,
  671. "gerber_circle_steps": 128,
  672. "gerber_use_buffer_for_union": True,
  673. # Gerber Advanced Options
  674. "gerber_aperture_display": False,
  675. "gerber_aperture_scale_factor": 1.0,
  676. "gerber_aperture_buffer_factor": 0.0,
  677. "gerber_follow": False,
  678. # Gerber Export
  679. "gerber_exp_units": 'IN',
  680. "gerber_exp_integer": 2,
  681. "gerber_exp_decimals": 4,
  682. "gerber_exp_zeros": 'L',
  683. # Gerber Editor
  684. "gerber_editor_sel_limit": 30,
  685. "gerber_editor_newcode": 10,
  686. "gerber_editor_newsize": 0.8,
  687. "gerber_editor_newtype": 'C',
  688. "gerber_editor_newdim": "0.5, 0.5",
  689. "gerber_editor_array_size": 5,
  690. "gerber_editor_lin_axis": 'X',
  691. "gerber_editor_lin_pitch": 1,
  692. "gerber_editor_lin_angle": 0.0,
  693. "gerber_editor_circ_dir": 'CW',
  694. "gerber_editor_circ_angle": 0.0,
  695. "gerber_editor_scale_f": 1.0,
  696. "gerber_editor_buff_f": 0.1,
  697. "gerber_editor_ma_low": 0.0,
  698. "gerber_editor_ma_high": 1.0,
  699. # Excellon General
  700. "excellon_plot": True,
  701. "excellon_solid": True,
  702. "excellon_format_upper_in": 2,
  703. "excellon_format_lower_in": 4,
  704. "excellon_format_upper_mm": 3,
  705. "excellon_format_lower_mm": 3,
  706. "excellon_zeros": "L",
  707. "excellon_units": "INCH",
  708. "excellon_optimization_type": 'B',
  709. "excellon_search_time": 3,
  710. # Excellon Options
  711. "excellon_drillz": -0.0590551,
  712. "excellon_travelz": 0.0787402,
  713. "excellon_feedrate": 3.14961,
  714. "excellon_spindlespeed": None,
  715. "excellon_spindledir": 'CW',
  716. "excellon_dwell": False,
  717. "excellon_dwelltime": 1,
  718. "excellon_toolchange": False,
  719. "excellon_toolchangez": 0.5,
  720. "excellon_ppname_e": 'default',
  721. "excellon_tooldia": 0.0314961,
  722. "excellon_slot_tooldia": 0.0708661,
  723. "excellon_gcode_type": "drills",
  724. # Excellon Advanced Options
  725. "excellon_offset": 0.0,
  726. "excellon_toolchangexy": "0.0, 0.0",
  727. "excellon_startz": None,
  728. "excellon_endz": 0.5,
  729. "excellon_feedrate_rapid": 31.4961,
  730. "excellon_z_pdepth": -0.02,
  731. "excellon_feedrate_probe": 3.14961,
  732. "excellon_f_plunge": False,
  733. "excellon_f_retract": False,
  734. # Excellon Export
  735. "excellon_exp_units": 'INCH',
  736. "excellon_exp_format": 'ndec',
  737. "excellon_exp_integer": 2,
  738. "excellon_exp_decimals": 4,
  739. "excellon_exp_zeros": 'LZ',
  740. "excellon_exp_slot_type": 'routing',
  741. # Excellon Editor
  742. "excellon_editor_sel_limit": 30,
  743. "excellon_editor_newdia": 0.039,
  744. "excellon_editor_array_size": 5,
  745. "excellon_editor_lin_dir": 'X',
  746. "excellon_editor_lin_pitch": 0.1,
  747. "excellon_editor_lin_angle": 0.0,
  748. "excellon_editor_circ_dir": 'CW',
  749. "excellon_editor_circ_angle": 12,
  750. # Excellon Slots
  751. "excellon_editor_slot_direction": 'X',
  752. "excellon_editor_slot_angle": 0.0,
  753. "excellon_editor_slot_length": 5.0,
  754. # Excellon Slot Array
  755. "excellon_editor_slot_array_size": 5,
  756. "excellon_editor_slot_lin_dir": 'X',
  757. "excellon_editor_slot_lin_pitch": 0.1,
  758. "excellon_editor_slot_lin_angle": 0.0,
  759. "excellon_editor_slot_circ_dir": 'CW',
  760. "excellon_editor_slot_circ_angle": 0.0,
  761. # Geometry General
  762. "geometry_plot": True,
  763. "geometry_circle_steps": 128,
  764. "geometry_cnctooldia": "0.0944882",
  765. # Geometry Options
  766. "geometry_cutz": -0.0944882,
  767. "geometry_vtipdia": 0.1,
  768. "geometry_vtipangle": 30,
  769. "geometry_multidepth": False,
  770. "geometry_depthperpass": 0.0314961,
  771. "geometry_travelz": 0.0787402,
  772. "geometry_toolchange": False,
  773. "geometry_toolchangez": 0.5,
  774. "geometry_feedrate": 3.14961,
  775. "geometry_feedrate_z": 3.14961,
  776. "geometry_spindlespeed": None,
  777. "geometry_spindledir": 'CW',
  778. "geometry_dwell": False,
  779. "geometry_dwelltime": 1,
  780. "geometry_ppname_g": 'default',
  781. # Geometry Advanced Options
  782. "geometry_toolchangexy": "0.0, 0.0",
  783. "geometry_startz": None,
  784. "geometry_endz": 0.5,
  785. "geometry_feedrate_rapid": 3.14961,
  786. "geometry_extracut": False,
  787. "geometry_z_pdepth": -0.02,
  788. "geometry_f_plunge": False,
  789. "geometry_feedrate_probe": 3.14961,
  790. "geometry_segx": 0.0,
  791. "geometry_segy": 0.0,
  792. # Geometry Editor
  793. "geometry_editor_sel_limit": 30,
  794. # CNC Job General
  795. "cncjob_plot": True,
  796. "cncjob_plot_kind": 'all',
  797. "cncjob_annotation": True,
  798. "cncjob_annotation_fontsize": 9,
  799. "cncjob_annotation_fontcolor": '#990000',
  800. "cncjob_tooldia": 0.0393701,
  801. "cncjob_coords_decimals": 4,
  802. "cncjob_fr_decimals": 2,
  803. "cncjob_steps_per_circle": 128,
  804. # CNC Job Options
  805. "cncjob_prepend": "",
  806. "cncjob_append": "",
  807. # CNC Job Advanced Options
  808. "cncjob_toolchange_macro": "",
  809. "cncjob_toolchange_macro_enable": False,
  810. "tools_ncctools": "0.0393701, 0.019685",
  811. "tools_nccorder": 'rev',
  812. "tools_nccoverlap": 0.015748,
  813. "tools_nccmargin": 0.0393701,
  814. "tools_nccmethod": "seed",
  815. "tools_nccconnect": True,
  816. "tools_ncccontour": True,
  817. "tools_nccrest": False,
  818. "tools_ncc_offset_choice": False,
  819. "tools_ncc_offset_value": 0.0000,
  820. "tools_nccref": 'itself',
  821. "tools_cutouttooldia": 0.0944882,
  822. "tools_cutoutkind": "single",
  823. "tools_cutoutmargin": 0.00393701,
  824. "tools_cutoutgapsize": 0.15748,
  825. "tools_gaps_ff": "4",
  826. "tools_cutout_convexshape": False,
  827. "tools_painttooldia": 0.023622,
  828. "tools_paintorder": 'rev',
  829. "tools_paintoverlap": 0.015748,
  830. "tools_paintmargin": 0.0,
  831. "tools_paintmethod": "seed",
  832. "tools_selectmethod": "single",
  833. "tools_pathconnect": True,
  834. "tools_paintcontour": True,
  835. "tools_2sided_mirror_axis": "X",
  836. "tools_2sided_axis_loc": "point",
  837. "tools_2sided_drilldia": 0.0393701,
  838. "tools_film_type": 'neg',
  839. "tools_film_boundary": 0.0393701,
  840. "tools_film_scale": 0,
  841. "tools_panelize_spacing_columns": 0,
  842. "tools_panelize_spacing_rows": 0,
  843. "tools_panelize_columns": 1,
  844. "tools_panelize_rows": 1,
  845. "tools_panelize_constrain": False,
  846. "tools_panelize_constrainx": 0.0,
  847. "tools_panelize_constrainy": 0.0,
  848. "tools_panelize_panel_type": 'gerber',
  849. "tools_calc_vshape_tip_dia": 0.007874,
  850. "tools_calc_vshape_tip_angle": 30,
  851. "tools_calc_vshape_cut_z": 0.000787,
  852. "tools_calc_electro_length": 10.0,
  853. "tools_calc_electro_width": 10.0,
  854. "tools_calc_electro_cdensity": 13.0,
  855. "tools_calc_electro_growth": 10.0,
  856. "tools_transform_rotate": 90,
  857. "tools_transform_skew_x": 0.0,
  858. "tools_transform_skew_y": 0.0,
  859. "tools_transform_scale_x": 1.0,
  860. "tools_transform_scale_y": 1.0,
  861. "tools_transform_scale_link": True,
  862. "tools_transform_scale_reference": True,
  863. "tools_transform_offset_x": 0.0,
  864. "tools_transform_offset_y": 0.0,
  865. "tools_transform_mirror_reference": False,
  866. "tools_transform_mirror_point": (0, 0),
  867. "tools_solderpaste_tools": "0.0393701, 0.011811",
  868. "tools_solderpaste_new": 0.011811,
  869. "tools_solderpaste_z_start": 0.00019685039,
  870. "tools_solderpaste_z_dispense": 0.00393701,
  871. "tools_solderpaste_z_stop": 0.00019685039,
  872. "tools_solderpaste_z_travel": 0.00393701,
  873. "tools_solderpaste_z_toolchange": 0.0393701,
  874. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  875. "tools_solderpaste_frxy": 3.0,
  876. "tools_solderpaste_frz": 3.0,
  877. "tools_solderpaste_frz_dispense": 0.0393701,
  878. "tools_solderpaste_speedfwd": 20,
  879. "tools_solderpaste_dwellfwd": 1,
  880. "tools_solderpaste_speedrev": 10,
  881. "tools_solderpaste_dwellrev": 1,
  882. "tools_solderpaste_pp": 'Paste_1',
  883. "tools_sub_close_paths": True
  884. })
  885. # ##############################
  886. # ## Load defaults from file ###
  887. # ##############################
  888. if user_defaults:
  889. self.load_defaults(filename='current_defaults')
  890. # ###########################
  891. # #### APPLY APP LANGUAGE ###
  892. # ###########################
  893. ret_val = fcTranslate.apply_language('strings')
  894. if ret_val == "no language":
  895. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  896. log.debug("Could not find the Language files. The App strings are missing.")
  897. else:
  898. # make the current language the current selection on the language combobox
  899. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  900. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  901. # ##################################
  902. # ### CREATE UNIQUE SERIAL NUMBER ##
  903. # ##################################
  904. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  905. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  906. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  907. self.save_defaults(silent=True)
  908. self.propagate_defaults(silent=True)
  909. self.restore_main_win_geom()
  910. def auto_save_defaults():
  911. try:
  912. self.save_defaults(silent=True)
  913. self.propagate_defaults(silent=True)
  914. finally:
  915. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  916. # the following lines activates automatic defaults save
  917. # if user_defaults:
  918. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  919. # self.options_form = PreferencesUI()
  920. self.options_form_fields = {
  921. "units": self.ui.general_options_form.general_app_group.units_radio,
  922. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  923. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  924. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  925. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  926. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  927. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  928. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  929. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  930. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  931. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  932. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  933. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  934. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  935. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  936. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  937. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  938. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  939. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  940. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  941. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  942. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  943. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  944. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  945. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  946. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  947. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  948. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  949. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  950. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  951. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  952. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  953. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  954. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  955. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  956. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  957. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  958. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  959. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  960. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  961. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  962. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  963. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  964. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  965. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  966. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  967. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  968. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  969. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  970. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  971. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  972. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  973. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  974. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  975. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  976. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  977. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  978. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  979. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  980. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  981. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  982. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  983. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  984. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  985. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  986. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  987. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  988. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  989. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  990. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  991. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  992. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  993. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  994. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  995. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  996. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  997. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  998. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  999. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1000. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1001. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1002. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1003. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1004. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1005. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1006. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1007. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1008. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1009. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1010. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1011. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1012. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1013. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1014. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1015. }
  1016. for name in list(self.postprocessors.keys()):
  1017. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1018. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1019. self.options = LoudDict()
  1020. self.options.set_change_callback(self.on_options_dict_change)
  1021. self.options.update({
  1022. "units": "IN",
  1023. "global_gridx": 1.0,
  1024. "global_gridy": 1.0,
  1025. "global_snap_max": 0.05,
  1026. "global_background_timeout": 300000, # Default value is 5 minutes
  1027. "global_verbose_error_level": 0, # Shell verbosity:
  1028. # 0 = default(python trace only for unknown errors),
  1029. # 1 = show trace(show trace allways), 2 = (For the future).
  1030. "gerber_plot": True,
  1031. "gerber_solid": True,
  1032. "gerber_multicolored": False,
  1033. "gerber_isotooldia": 0.016,
  1034. "gerber_isopasses": 1,
  1035. "gerber_isooverlap": 0.15,
  1036. "gerber_combine_passes": True,
  1037. "gerber_noncoppermargin": 0.0,
  1038. "gerber_noncopperrounded": False,
  1039. "gerber_bboxmargin": 0.0,
  1040. "gerber_bboxrounded": False,
  1041. "excellon_plot": True,
  1042. "excellon_solid": False,
  1043. "excellon_format_upper_in": 2,
  1044. "excellon_format_lower_in": 4,
  1045. "excellon_format_upper_mm": 3,
  1046. "excellon_format_lower_mm": 3,
  1047. "excellon_units": 'INCH',
  1048. "excellon_optimization_type": 'B',
  1049. "excellon_search_time": 3,
  1050. "excellon_zeros": "L",
  1051. "excellon_drillz": -0.1,
  1052. "excellon_travelz": 0.1,
  1053. "excellon_feedrate": 3.0,
  1054. "excellon_feedrate_rapid": 3.0,
  1055. "excellon_spindlespeed": None,
  1056. "excellon_spindledir": 'CW',
  1057. "excellon_dwell": True,
  1058. "excellon_dwelltime": 1000,
  1059. "excellon_toolchange": False,
  1060. "excellon_toolchangez": 1.0,
  1061. "excellon_toolchangexy": "0.0, 0.0",
  1062. "excellon_tooldia": 0.016,
  1063. "excellon_ppname_e": 'default',
  1064. "excellon_f_plunge": False,
  1065. "excellon_startz": None,
  1066. "excellon_endz": 2.0,
  1067. "geometry_plot": True,
  1068. "geometry_segx": 0.0,
  1069. "geometry_segy": 0.0,
  1070. "geometry_cutz": -0.002,
  1071. "geometry_vtipdia": 0.1,
  1072. "geometry_vtipangle": 30,
  1073. "geometry_travelz": 0.1,
  1074. "geometry_feedrate": 3.0,
  1075. "geometry_feedrate_z": 3.0,
  1076. "geometry_feedrate_rapid": 3.0,
  1077. "geometry_spindlespeed": None,
  1078. "geometry_spindledir": 'CW',
  1079. "geometry_dwell": True,
  1080. "geometry_dwelltime": 1000,
  1081. "geometry_cnctooldia": 0.016,
  1082. "geometry_toolchange": False,
  1083. "geometry_toolchangez": 2.0,
  1084. "geometry_toolchangexy": "0.0, 0.0",
  1085. "geometry_startz": None,
  1086. "geometry_endz": 2.0,
  1087. "geometry_ppname_g": "default",
  1088. "geometry_f_plunge": False,
  1089. "geometry_depthperpass": 0.002,
  1090. "geometry_multidepth": False,
  1091. "geometry_extracut": False,
  1092. "cncjob_plot": True,
  1093. "cncjob_tooldia": 0.016,
  1094. "cncjob_prepend": "",
  1095. "cncjob_append": "",
  1096. "tools_ncctools": "1.0, 0.5",
  1097. "tools_nccoverlap": 0.4,
  1098. "tools_nccmargin": 1,
  1099. "tools_cutouttooldia": 0.07,
  1100. "tools_cutoutmargin": 0.1,
  1101. "tools_cutoutgapsize": 0.15,
  1102. "tools_gaps_ff": "8",
  1103. "tools_painttooldia": 0.07,
  1104. "tools_paintoverlap": 0.15,
  1105. "tools_paintmargin": 0.0,
  1106. "tools_paintmethod": "seed",
  1107. "tools_selectmethod": "single",
  1108. "tools_pathconnect": True,
  1109. "tools_paintcontour": True,
  1110. "tools_2sided_mirror_axis": "X",
  1111. "tools_2sided_axis_loc": 'point',
  1112. "tools_2sided_drilldia": 1,
  1113. "tools_film_type": 'neg',
  1114. "tools_film_boundary": 1,
  1115. "tools_film_scale": 0,
  1116. "tools_panelize_spacing_columns": 0,
  1117. "tools_panelize_spacing_rows": 0,
  1118. "tools_panelize_columns": 1,
  1119. "tools_panelize_rows": 1,
  1120. "tools_panelize_constrain": False,
  1121. "tools_panelize_constrainx": 0.0,
  1122. "tools_panelize_constrainy": 0.0
  1123. })
  1124. self.options.update(self.defaults) # Copy app defaults to project options
  1125. self.gen_form = None
  1126. self.ger_form = None
  1127. self.exc_form = None
  1128. self.geo_form = None
  1129. self.cnc_form = None
  1130. self.tools_form = None
  1131. self.on_options_combo_change(0) # Will show the initial form
  1132. # ################################
  1133. # ### Initialize the color box's color in Preferences -> Global -> Color
  1134. # Init Plot Colors
  1135. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1136. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1137. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1138. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1139. int(self.defaults['global_plot_fill'][7:9], 16))
  1140. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1141. int(self.defaults['global_plot_fill'][7:9], 16))
  1142. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1143. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1144. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1145. # Init Left-Right Selection colors
  1146. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1147. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1148. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1149. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1150. int(self.defaults['global_sel_fill'][7:9], 16))
  1151. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1152. int(self.defaults['global_sel_fill'][7:9], 16))
  1153. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1154. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1155. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1156. # Init Right-Left Selection colors
  1157. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1158. self.defaults['global_alt_sel_fill'])
  1159. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1160. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1161. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1162. int(self.defaults['global_sel_fill'][7:9], 16))
  1163. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1164. int(self.defaults['global_sel_fill'][7:9], 16))
  1165. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1166. self.defaults['global_alt_sel_line'])
  1167. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1168. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1169. # Init Draw color and Selection Draw Color
  1170. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1171. self.defaults['global_draw_color'])
  1172. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1173. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1174. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1175. self.defaults['global_sel_draw_color'])
  1176. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1177. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1178. # Init Project Items color
  1179. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1180. self.defaults['global_proj_item_color'])
  1181. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1182. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1183. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1184. self.defaults['global_proj_item_dis_color'])
  1185. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1186. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1187. # Init the Annotation CNC Job color
  1188. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(
  1189. self.defaults['cncjob_annotation_fontcolor'])
  1190. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  1191. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1192. # ### End of Data ####
  1193. # ###############################################
  1194. # ############# SETUP Plot Area #################
  1195. # ###############################################
  1196. start_plot_time = time.time() # debug
  1197. self.plotcanvas = None
  1198. self.app_cursor = None
  1199. self.hover_shapes = None
  1200. self.on_plotcanvas_setup()
  1201. end_plot_time = time.time()
  1202. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1203. self.ui.splitter.setStretchFactor(1, 2)
  1204. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1205. # depending on from where those tools are called different actions can be done
  1206. self.call_source = 'app'
  1207. # ##############################################
  1208. # ######### SETUP OBJECT COLLECTION ############
  1209. # ##############################################
  1210. self.collection = ObjectCollection(self)
  1211. self.ui.project_tab_layout.addWidget(self.collection.view)
  1212. # ### Adjust tabs width ## ##
  1213. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1214. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1215. self.collection.view.setMinimumWidth(290)
  1216. self.log.debug("Finished creating Object Collection.")
  1217. # ###############################################
  1218. # ############# Worker SETUP ####################
  1219. # ###############################################
  1220. if self.defaults["global_worker_number"]:
  1221. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1222. else:
  1223. self.workers = WorkerStack(workers_number=2)
  1224. self.worker_task.connect(self.workers.add_task)
  1225. self.log.debug("Finished creating Workers crew.")
  1226. # ################################################
  1227. # ############### Signal handling ################
  1228. # ################################################
  1229. # ### Custom signals ###
  1230. self.inform.connect(self.info)
  1231. self.app_quit.connect(self.quit_application)
  1232. self.message.connect(self.message_dialog)
  1233. self.progress.connect(self.set_progress_bar)
  1234. self.object_created.connect(self.on_object_created)
  1235. self.object_changed.connect(self.on_object_changed)
  1236. self.object_plotted.connect(self.on_object_plotted)
  1237. self.plots_updated.connect(self.on_plots_updated)
  1238. self.file_opened.connect(self.register_recent)
  1239. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1240. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1241. # ### Standard signals
  1242. # ### Menu
  1243. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1244. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1245. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1246. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1247. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1248. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1249. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1250. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1251. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1252. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1253. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1254. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1255. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1256. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1257. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1258. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1259. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1260. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1261. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1262. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1263. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1264. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1265. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1266. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1267. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1268. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1269. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1270. self.ui.menufile_exit.triggered.connect(self.final_save)
  1271. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1272. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1273. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1274. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1275. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1276. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1277. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1278. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1279. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1280. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1281. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1282. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1283. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1284. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1285. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1286. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1287. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1288. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1289. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1290. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1291. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1292. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1293. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1294. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1295. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1296. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1297. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1298. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1299. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1300. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1301. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1302. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1303. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1304. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1305. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1306. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1307. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1308. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1309. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1310. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1311. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1312. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1313. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1314. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1315. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1316. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1317. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1318. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1319. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1320. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1321. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1322. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1323. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1324. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1325. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1326. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1327. # ToolBar signals
  1328. self.connect_toolbar_signals()
  1329. # Notebook signals
  1330. # make the right click on the notebook tab connect to a function
  1331. self.ui.notebook.setupContextMenu()
  1332. self.ui.notebook.addContextMenu(
  1333. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1334. initial_checked=self.defaults["global_tabs_detachable"])
  1335. # activate initial state
  1336. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1337. # Context Menu
  1338. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1339. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1340. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1341. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1342. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1343. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1344. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1345. self.ui.clearplot.triggered.connect(self.clear_plots)
  1346. self.ui.replot.triggered.connect(self.plot_all)
  1347. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1348. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1349. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1350. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1351. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1352. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1353. # Preferences Plot Area TAB
  1354. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1355. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1356. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1357. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1358. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1359. # ##############################
  1360. # ### GUI PREFERENCES SIGNALS ##
  1361. # ##############################
  1362. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1363. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1364. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1365. )
  1366. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1367. lambda: self.on_toggle_units(no_pref=False))
  1368. # ##############################
  1369. # ### GUI PREFERENCES SIGNALS ##
  1370. # ##############################
  1371. # Setting plot colors signals
  1372. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1373. self.on_pf_color_entry)
  1374. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1375. self.on_pf_color_button)
  1376. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1377. self.on_pf_color_spinner)
  1378. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1379. self.on_pf_color_slider)
  1380. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1381. self.on_pl_color_entry)
  1382. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1383. self.on_pl_color_button)
  1384. # Setting selection (left - right) colors signals
  1385. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1386. self.on_sf_color_entry)
  1387. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1388. self.on_sf_color_button)
  1389. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1390. self.on_sf_color_spinner)
  1391. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1392. self.on_sf_color_slider)
  1393. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1394. self.on_sl_color_entry)
  1395. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1396. self.on_sl_color_button)
  1397. # Setting selection (right - left) colors signals
  1398. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1399. self.on_alt_sf_color_entry)
  1400. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1401. self.on_alt_sf_color_button)
  1402. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1403. self.on_alt_sf_color_spinner)
  1404. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1405. self.on_alt_sf_color_slider)
  1406. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1407. self.on_alt_sl_color_entry)
  1408. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1409. self.on_alt_sl_color_button)
  1410. # Setting Editor Draw colors signals
  1411. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1412. self.on_draw_color_entry)
  1413. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1414. self.on_draw_color_button)
  1415. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1416. self.on_sel_draw_color_entry)
  1417. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1418. self.on_sel_draw_color_button)
  1419. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1420. self.on_proj_color_entry)
  1421. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1422. self.on_proj_color_button)
  1423. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1424. self.on_proj_color_dis_entry)
  1425. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1426. self.on_proj_color_dis_button)
  1427. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1428. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1429. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1430. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1431. self.on_cnc_custom_parameters)
  1432. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.editingFinished.connect(
  1433. self.on_annotation_fontcolor_entry)
  1434. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.clicked.connect(
  1435. self.on_annotation_fontcolor_button)
  1436. # Modify G-CODE Plot Area TAB
  1437. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1438. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1439. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1440. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1441. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1442. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1443. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1444. # portability changed
  1445. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1446. # Object list
  1447. self.collection.view.activated.connect(self.on_row_activated)
  1448. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1449. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1450. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1451. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1452. self.on_excellon_defaults_button)
  1453. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1454. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1455. self.on_excellon_options_button)
  1456. # when there are arguments at application startup this get launched
  1457. self.args_at_startup.connect(self.on_startup_args)
  1458. self.log.debug("Finished connecting Signals.")
  1459. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1460. self.tool_tab_locked = False
  1461. # decide if to show or hide the Notebook side of the screen at startup
  1462. if self.defaults["global_project_at_startup"] is True:
  1463. self.ui.splitter.setSizes([1, 1])
  1464. else:
  1465. self.ui.splitter.setSizes([0, 1])
  1466. # ###########################################
  1467. # ################# Other setups ############
  1468. # ###########################################
  1469. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1470. self.setup_obj_classes()
  1471. self.setup_recent_items()
  1472. self.setup_component_editor()
  1473. # ###########################################
  1474. # #######Auto-complete KEYWORDS #############
  1475. # ###########################################
  1476. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1477. 'aligndrill', 'clear',
  1478. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1479. 'export_gcode',
  1480. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1481. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1482. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1483. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1484. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1485. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1486. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1487. ]
  1488. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1489. 'holes', 'grid', 'minoffset', 'gridoffset', 'axisoffset', 'dia', 'dist',
  1490. 'gridoffsetx', 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate',
  1491. 'feedrate_rapid', 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g',
  1492. 'outname', 'margin', 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed',
  1493. 'toolchange', 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble',
  1494. 'filename', 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads',
  1495. 'x', 'y', 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value',
  1496. 'angle_x', 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1497. ]
  1498. self.tcl_keywords = [
  1499. "after", "append", "apply", "array", "auto_execok", "auto_import", "auto_load", "auto_mkindex",
  1500. "auto_qualify", "auto_reset", "bgerror", "binary", "break", "case", "catch", "cd", "chan", "clock", "close",
  1501. "concat", "continue", "coroutine", "dict", "encoding", "eof", "error", "eval", "exec", "exit", "expr",
  1502. "fblocked", "fconfigure", "fcopy", "file", "fileevent", "flush", "for", "foreach", "format", "gets", "glob",
  1503. "global", "history", "if", "incr", "info", "interp", "join", "lappend", "lassign", "lindex", "linsert",
  1504. "list", "llength", "load", "lrange", "lrepeat", "lreplace", "lreverse", "lsearch", "lset", "lsort",
  1505. "mathfunc", "mathop", "memory", "my", "namespace", "next", "nextto", "open", "package", "parray", "pid",
  1506. "pkg_mkIndex", "platform", "proc", "puts", "pwd", "read", "refchan", "regexp", "regsub", "rename", "return",
  1507. "scan", "seek", "self", "set", "socket", "source", "split", "string", "subst", "switch", "tailcall",
  1508. "tcl_endOfWord", "tcl_findLibrary", "tcl_startOfNextWord", "tcl_startOfPreviousWord", "tcl_wordBreakAfter",
  1509. "tcl_wordBreakBefore", "tell", "throw", "time", "tm", "trace", "transchan", "try", "unknown", "unload",
  1510. "unset", "update", "uplevel", "upvar", "variable", "vwait", "while", "yield", "yieldto", "zlib",
  1511. "attemptckalloc", "attemptckrealloc", "ckalloc", "ckfree", "ckrealloc", "Tcl_Access", "Tcl_AddErrorInfo",
  1512. "Tcl_AddObjErrorInfo", "Tcl_AlertNotifier", "Tcl_Alloc", "Tcl_AllocStatBuf", "Tcl_AllowExceptions",
  1513. "Tcl_AppendAllObjTypes", "Tcl_AppendElement", "Tcl_AppendExportList", "Tcl_AppendFormatToObj",
  1514. "Tcl_AppendLimitedToObj", "Tcl_AppendObjToErrorInfo", "Tcl_AppendObjToObj", "Tcl_AppendPrintfToObj",
  1515. "Tcl_AppendResult", "Tcl_AppendResultVA", "Tcl_AppendStringsToObj", "Tcl_AppendStringsToObjVA",
  1516. "Tcl_AppendToObj", "Tcl_AppendUnicodeToObj", "Tcl_AppInit", "Tcl_AsyncCreate", "Tcl_AsyncDelete",
  1517. "Tcl_AsyncInvoke", "Tcl_AsyncMark", "Tcl_AsyncReady", "Tcl_AttemptAlloc", "Tcl_AttemptRealloc",
  1518. "Tcl_AttemptSetObjLength", "Tcl_BackgroundError", "Tcl_BackgroundException", "Tcl_Backslash",
  1519. "Tcl_BadChannelOption", "Tcl_CallWhenDeleted", "Tcl_Canceled", "Tcl_CancelEval", "Tcl_CancelIdleCall",
  1520. "Tcl_ChannelBlockModeProc", "Tcl_ChannelBuffered", "Tcl_ChannelClose2Proc", "Tcl_ChannelCloseProc",
  1521. "Tcl_ChannelFlushProc", "Tcl_ChannelGetHandleProc", "Tcl_ChannelGetOptionProc", "Tcl_ChannelHandlerProc",
  1522. "Tcl_ChannelInputProc", "Tcl_ChannelName", "Tcl_ChannelOutputProc", "Tcl_ChannelSeekProc",
  1523. "Tcl_ChannelSetOptionProc", "Tcl_ChannelThreadActionProc", "Tcl_ChannelTruncateProc", "Tcl_ChannelVersion",
  1524. "Tcl_ChannelWatchProc", "Tcl_ChannelWideSeekProc", "Tcl_Chdir", "Tcl_ClassGetMetadata",
  1525. "Tcl_ClassSetConstructor", "Tcl_ClassSetDestructor", "Tcl_ClassSetMetadata", "Tcl_ClearChannelHandlers",
  1526. "Tcl_Close", "Tcl_CommandComplete", "Tcl_CommandTraceInfo", "Tcl_Concat", "Tcl_ConcatObj",
  1527. "Tcl_ConditionFinalize", "Tcl_ConditionNotify", "Tcl_ConditionWait", "Tcl_ConvertCountedElement",
  1528. "Tcl_ConvertElement", "Tcl_ConvertToType", "Tcl_CopyObjectInstance", "Tcl_CreateAlias",
  1529. "Tcl_CreateAliasObj", "Tcl_CreateChannel", "Tcl_CreateChannelHandler", "Tcl_CreateCloseHandler",
  1530. "Tcl_CreateCommand", "Tcl_CreateEncoding", "Tcl_CreateEnsemble", "Tcl_CreateEventSource",
  1531. "Tcl_CreateExitHandler", "Tcl_CreateFileHandler", "Tcl_CreateHashEntry", "Tcl_CreateInterp",
  1532. "Tcl_CreateMathFunc", "Tcl_CreateNamespace", "Tcl_CreateObjCommand", "Tcl_CreateObjTrace",
  1533. "Tcl_CreateSlave", "Tcl_CreateThread", "Tcl_CreateThreadExitHandler", "Tcl_CreateTimerHandler",
  1534. "Tcl_CreateTrace", "Tcl_CutChannel", "Tcl_DecrRefCount", "Tcl_DeleteAssocData", "Tcl_DeleteChannelHandler",
  1535. "Tcl_DeleteCloseHandler", "Tcl_DeleteCommand", "Tcl_DeleteCommandFromToken", "Tcl_DeleteEvents",
  1536. "Tcl_DeleteEventSource", "Tcl_DeleteExitHandler", "Tcl_DeleteFileHandler", "Tcl_DeleteHashEntry",
  1537. "Tcl_DeleteHashTable", "Tcl_DeleteInterp", "Tcl_DeleteNamespace", "Tcl_DeleteThreadExitHandler",
  1538. "Tcl_DeleteTimerHandler", "Tcl_DeleteTrace", "Tcl_DetachChannel", "Tcl_DetachPids", "Tcl_DictObjDone",
  1539. "Tcl_DictObjFirst", "Tcl_DictObjGet", "Tcl_DictObjNext", "Tcl_DictObjPut", "Tcl_DictObjPutKeyList",
  1540. "Tcl_DictObjRemove", "Tcl_DictObjRemoveKeyList", "Tcl_DictObjSize", "Tcl_DiscardInterpState",
  1541. "Tcl_DiscardResult", "Tcl_DontCallWhenDeleted", "Tcl_DoOneEvent", "Tcl_DoWhenIdle", "Tcl_DStringAppend",
  1542. "Tcl_DStringAppendElement", "Tcl_DStringEndSublist", "Tcl_DStringFree", "Tcl_DStringGetResult",
  1543. "Tcl_DStringInit", "Tcl_DStringLength", "Tcl_DStringResult", "Tcl_DStringSetLength",
  1544. "Tcl_DStringStartSublist", "Tcl_DStringTrunc", "Tcl_DStringValue", "Tcl_DumpActiveMemory",
  1545. "Tcl_DuplicateObj", "Tcl_Eof", "Tcl_ErrnoId", "Tcl_ErrnoMsg", "Tcl_Eval", "Tcl_EvalEx", "Tcl_EvalFile",
  1546. "Tcl_EvalObjEx", "Tcl_EvalObjv", "Tcl_EvalTokens", "Tcl_EvalTokensStandard", "Tcl_EventuallyFree",
  1547. "Tcl_Exit", "Tcl_ExitThread", "Tcl_Export", "Tcl_ExposeCommand", "Tcl_ExprBoolean", "Tcl_ExprBooleanObj",
  1548. "Tcl_ExprDouble", "Tcl_ExprDoubleObj", "Tcl_ExprLong", "Tcl_ExprLongObj", "Tcl_ExprObj", "Tcl_ExprString",
  1549. "Tcl_ExternalToUtf", "Tcl_ExternalToUtfDString", "Tcl_Finalize", "Tcl_FinalizeNotifier",
  1550. "Tcl_FinalizeThread", "Tcl_FindCommand", "Tcl_FindEnsemble", "Tcl_FindExecutable", "Tcl_FindHashEntry",
  1551. "Tcl_FindNamespace", "Tcl_FirstHashEntry", "Tcl_Flush", "Tcl_ForgetImport", "Tcl_Format",
  1552. "Tcl_Free· Tcl_FreeEncoding", "Tcl_FreeParse", "Tcl_FreeResult", "Tcl_FSAccess", "Tcl_FSChdir",
  1553. "Tcl_FSConvertToPathType", "Tcl_FSCopyDirectory", "Tcl_FSCopyFile", "Tcl_FSCreateDirectory", "Tcl_FSData",
  1554. "Tcl_FSDeleteFile", "Tcl_FSEqualPaths", "Tcl_FSEvalFile", "Tcl_FSEvalFileEx", "Tcl_FSFileAttrsGet",
  1555. "Tcl_FSFileAttrsSet", "Tcl_FSFileAttrStrings", "Tcl_FSFileSystemInfo", "Tcl_FSGetCwd",
  1556. "Tcl_FSGetFileSystemForPath", "Tcl_FSGetInternalRep", "Tcl_FSGetNativePath", "Tcl_FSGetNormalizedPath",
  1557. "Tcl_FSGetPathType", "Tcl_FSGetTranslatedPath", "Tcl_FSGetTranslatedStringPath", "Tcl_FSJoinPath",
  1558. "Tcl_FSJoinToPath", "Tcl_FSLink· Tcl_FSListVolumes", "Tcl_FSLoadFile", "Tcl_FSLstat",
  1559. "Tcl_FSMatchInDirectory", "Tcl_FSMountsChanged", "Tcl_FSNewNativePath", "Tcl_FSOpenFileChannel",
  1560. "Tcl_FSPathSeparator", "Tcl_FSRegister", "Tcl_FSRemoveDirectory", "Tcl_FSRenameFile", "Tcl_FSSplitPath",
  1561. "Tcl_FSStat", "Tcl_FSUnloadFile", "Tcl_FSUnregister", "Tcl_FSUtime", "Tcl_GetAccessTimeFromStat",
  1562. "Tcl_GetAlias", "Tcl_GetAliasObj", "Tcl_GetAssocData", "Tcl_GetBignumFromObj", "Tcl_GetBlocksFromStat",
  1563. "Tcl_GetBlockSizeFromStat", "Tcl_GetBoolean", "Tcl_GetBooleanFromObj", "Tcl_GetByteArrayFromObj",
  1564. "Tcl_GetChangeTimeFromStat", "Tcl_GetChannel", "Tcl_GetChannelBufferSize", "Tcl_GetChannelError",
  1565. "Tcl_GetChannelErrorInterp", "Tcl_GetChannelHandle", "Tcl_GetChannelInstanceData", "Tcl_GetChannelMode",
  1566. "Tcl_GetChannelName", "Tcl_GetChannelNames", "Tcl_GetChannelNamesEx", "Tcl_GetChannelOption",
  1567. "Tcl_GetChannelThread", "Tcl_GetChannelType", "Tcl_GetCharLength", "Tcl_GetClassAsObject",
  1568. "Tcl_GetCommandFromObj", "Tcl_GetCommandFullName", "Tcl_GetCommandInfo", "Tcl_GetCommandInfoFromToken",
  1569. "Tcl_GetCommandName", "Tcl_GetCurrentNamespace", "Tcl_GetCurrentThread", "Tcl_GetCwd",
  1570. "Tcl_GetDefaultEncodingDir", "Tcl_GetDeviceTypeFromStat", "Tcl_GetDouble", "Tcl_GetDoubleFromObj",
  1571. "Tcl_GetEncoding", "Tcl_GetEncodingFromObj", "Tcl_GetEncodingName", "Tcl_GetEncodingNameFromEnvironment",
  1572. "Tcl_GetEncodingNames", "Tcl_GetEncodingSearchPath", "Tcl_GetEnsembleFlags", "Tcl_GetEnsembleMappingDict",
  1573. "Tcl_GetEnsembleNamespace", "Tcl_GetEnsembleParameterList", "Tcl_GetEnsembleSubcommandList",
  1574. "Tcl_GetEnsembleUnknownHandler", "Tcl_GetErrno", "Tcl_GetErrorLine", "Tcl_GetFSDeviceFromStat",
  1575. "Tcl_GetFSInodeFromStat", "Tcl_GetGlobalNamespace", "Tcl_GetGroupIdFromStat", "Tcl_GetHashKey",
  1576. "Tcl_GetHashValue", "Tcl_GetHostName", "Tcl_GetIndexFromObj", "Tcl_GetIndexFromObjStruct", "Tcl_GetInt",
  1577. "Tcl_GetInterpPath", "Tcl_GetIntFromObj", "Tcl_GetLinkCountFromStat", "Tcl_GetLongFromObj", "Tcl_GetMaster",
  1578. "Tcl_GetMathFuncInfo", "Tcl_GetModeFromStat", "Tcl_GetModificationTimeFromStat", "Tcl_GetNameOfExecutable",
  1579. "Tcl_GetNamespaceUnknownHandler", "Tcl_GetObjectAsClass", "Tcl_GetObjectCommand", "Tcl_GetObjectFromObj",
  1580. "Tcl_GetObjectName", "Tcl_GetObjectNamespace", "Tcl_GetObjResult", "Tcl_GetObjType", "Tcl_GetOpenFile",
  1581. "Tcl_GetPathType", "Tcl_GetRange", "Tcl_GetRegExpFromObj", "Tcl_GetReturnOptions", "Tcl_Gets",
  1582. "Tcl_GetServiceMode", "Tcl_GetSizeFromStat", "Tcl_GetSlave", "Tcl_GetsObj", "Tcl_GetStackedChannel",
  1583. "Tcl_GetStartupScript", "Tcl_GetStdChannel", "Tcl_GetString", "Tcl_GetStringFromObj", "Tcl_GetStringResult",
  1584. "Tcl_GetThreadData", "Tcl_GetTime", "Tcl_GetTopChannel", "Tcl_GetUniChar", "Tcl_GetUnicode",
  1585. "Tcl_GetUnicodeFromObj", "Tcl_GetUserIdFromStat", "Tcl_GetVar", "Tcl_GetVar2", "Tcl_GetVar2Ex",
  1586. "Tcl_GetVersion", "Tcl_GetWideIntFromObj", "Tcl_GlobalEval", "Tcl_GlobalEvalObj", "Tcl_HashStats",
  1587. "Tcl_HideCommand", "Tcl_Import", "Tcl_IncrRefCount", "Tcl_Init", "Tcl_InitCustomHashTable",
  1588. "Tcl_InitHashTable", "Tcl_InitMemory", "Tcl_InitNotifier", "Tcl_InitObjHashTable", "Tcl_InitStubs",
  1589. "Tcl_InputBlocked", "Tcl_InputBuffered", "Tcl_InterpActive", "Tcl_InterpDeleted", "Tcl_InvalidateStringRep",
  1590. "Tcl_IsChannelExisting", "Tcl_IsChannelRegistered", "Tcl_IsChannelShared", "Tcl_IsEnsemble", "Tcl_IsSafe",
  1591. "Tcl_IsShared", "Tcl_IsStandardChannel", "Tcl_JoinPath", "Tcl_JoinThread", "Tcl_LimitAddHandler",
  1592. "Tcl_LimitCheck", "Tcl_LimitExceeded", "Tcl_LimitGetCommands", "Tcl_LimitGetGranularity",
  1593. "Tcl_LimitGetTime", "Tcl_LimitReady", "Tcl_LimitRemoveHandler", "Tcl_LimitSetCommands",
  1594. "Tcl_LimitSetGranularity", "Tcl_LimitSetTime", "Tcl_LimitTypeEnabled", "Tcl_LimitTypeExceeded",
  1595. "Tcl_LimitTypeReset", "Tcl_LimitTypeSet", "Tcl_LinkVar", "Tcl_ListMathFuncs", "Tcl_ListObjAppendElement",
  1596. "Tcl_ListObjAppendList", "Tcl_ListObjGetElements", "Tcl_ListObjIndex", "Tcl_ListObjLength",
  1597. "Tcl_ListObjReplace", "Tcl_LogCommandInfo", "Tcl_Main", "Tcl_MakeFileChannel", "Tcl_MakeSafe",
  1598. "Tcl_MakeTcpClientChannel", "Tcl_Merge", "Tcl_MethodDeclarerClass", "Tcl_MethodDeclarerObject",
  1599. "Tcl_MethodIsPublic", "Tcl_MethodIsType", "Tcl_MethodName", "Tcl_MutexFinalize", "Tcl_MutexLock",
  1600. "Tcl_MutexUnlock", "Tcl_NewBignumObj", "Tcl_NewBooleanObj", "Tcl_NewByteArrayObj", "Tcl_NewDictObj",
  1601. "Tcl_NewDoubleObj", "Tcl_NewInstanceMethod", "Tcl_NewIntObj", "Tcl_NewListObj", "Tcl_NewLongObj",
  1602. "Tcl_NewMethod", "Tcl_NewObj", "Tcl_NewObjectInstance", "Tcl_NewStringObj", "Tcl_NewUnicodeObj",
  1603. "Tcl_NewWideIntObj", "Tcl_NextHashEntry", "Tcl_NotifyChannel", "Tcl_NRAddCallback", "Tcl_NRCallObjProc",
  1604. "Tcl_NRCmdSwap", "Tcl_NRCreateCommand", "Tcl_NREvalObj", "Tcl_NREvalObjv", "Tcl_NumUtfChars",
  1605. "Tcl_ObjectContextInvokeNext", "Tcl_ObjectContextIsFiltering", "Tcl_ObjectContextMethod",
  1606. "Tcl_ObjectContextObject", "Tcl_ObjectContextSkippedArgs", "Tcl_ObjectDeleted", "Tcl_ObjectGetMetadata",
  1607. "Tcl_ObjectGetMethodNameMapper", "Tcl_ObjectSetMetadata", "Tcl_ObjectSetMethodNameMapper", "Tcl_ObjGetVar2",
  1608. "Tcl_ObjPrintf", "Tcl_ObjSetVar2", "Tcl_OpenCommandChannel", "Tcl_OpenFileChannel", "Tcl_OpenTcpClient",
  1609. "Tcl_OpenTcpServer", "Tcl_OutputBuffered", "Tcl_Panic", "Tcl_PanicVA", "Tcl_ParseArgsObjv",
  1610. "Tcl_ParseBraces", "Tcl_ParseCommand", "Tcl_ParseExpr", "Tcl_ParseQuotedString", "Tcl_ParseVar",
  1611. "Tcl_ParseVarName", "Tcl_PkgPresent", "Tcl_PkgPresentEx", "Tcl_PkgProvide", "Tcl_PkgProvideEx",
  1612. "Tcl_PkgRequire", "Tcl_PkgRequireEx", "Tcl_PkgRequireProc", "Tcl_PosixError", "Tcl_Preserve",
  1613. "Tcl_PrintDouble", "Tcl_PutEnv", "Tcl_QueryTimeProc", "Tcl_QueueEvent", "Tcl_Read", "Tcl_ReadChars",
  1614. "Tcl_ReadRaw", "Tcl_Realloc", "Tcl_ReapDetachedProcs", "Tcl_RecordAndEval", "Tcl_RecordAndEvalObj",
  1615. "Tcl_RegExpCompile", "Tcl_RegExpExec", "Tcl_RegExpExecObj", "Tcl_RegExpGetInfo", "Tcl_RegExpMatch",
  1616. "Tcl_RegExpMatchObj", "Tcl_RegExpRange", "Tcl_RegisterChannel", "Tcl_RegisterConfig", "Tcl_RegisterObjType",
  1617. "Tcl_Release", "Tcl_ResetResult", "Tcl_RestoreInterpState", "Tcl_RestoreResult", "Tcl_SaveInterpState",
  1618. "Tcl_SaveResult", "Tcl_ScanCountedElement", "Tcl_ScanElement", "Tcl_Seek", "Tcl_ServiceAll",
  1619. "Tcl_ServiceEvent", "Tcl_ServiceModeHook", "Tcl_SetAssocData", "Tcl_SetBignumObj", "Tcl_SetBooleanObj",
  1620. "Tcl_SetByteArrayLength", "Tcl_SetByteArrayObj", "Tcl_SetChannelBufferSize", "Tcl_SetChannelError",
  1621. "Tcl_SetChannelErrorInterp", "Tcl_SetChannelOption", "Tcl_SetCommandInfo", "Tcl_SetCommandInfoFromToken",
  1622. "Tcl_SetDefaultEncodingDir", "Tcl_SetDoubleObj", "Tcl_SetEncodingSearchPath", "Tcl_SetEnsembleFlags",
  1623. "Tcl_SetEnsembleMappingDict", "Tcl_SetEnsembleParameterList", "Tcl_SetEnsembleSubcommandList",
  1624. "Tcl_SetEnsembleUnknownHandler", "Tcl_SetErrno", "Tcl_SetErrorCode", "Tcl_SetErrorCodeVA",
  1625. "Tcl_SetErrorLine", "Tcl_SetExitProc", "Tcl_SetHashValue", "Tcl_SetIntObj", "Tcl_SetListObj",
  1626. "Tcl_SetLongObj", "Tcl_SetMainLoop", "Tcl_SetMaxBlockTime", "Tcl_SetNamespaceUnknownHandler",
  1627. "Tcl_SetNotifier", "Tcl_SetObjErrorCode", "Tcl_SetObjLength", "Tcl_SetObjResult", "Tcl_SetPanicProc",
  1628. "Tcl_SetRecursionLimit", "Tcl_SetResult", "Tcl_SetReturnOptions", "Tcl_SetServiceMode",
  1629. "Tcl_SetStartupScript", "Tcl_SetStdChannel", "Tcl_SetStringObj", "Tcl_SetSystemEncoding", "Tcl_SetTimeProc",
  1630. "Tcl_SetTimer", "Tcl_SetUnicodeObj", "Tcl_SetVar", "Tcl_SetVar2", "Tcl_SetVar2Ex", "Tcl_SetWideIntObj",
  1631. "Tcl_SignalId", "Tcl_SignalMsg", "Tcl_Sleep", "Tcl_SourceRCFile", "Tcl_SpliceChannel", "Tcl_SplitList",
  1632. "Tcl_SplitPath", "Tcl_StackChannel", "Tcl_StandardChannels", "Tcl_Stat", "Tcl_StaticPackage",
  1633. "Tcl_StringCaseMatch", "Tcl_StringMatch", "Tcl_SubstObj", "Tcl_TakeBignumFromObj", "Tcl_Tell",
  1634. "Tcl_ThreadAlert", "Tcl_ThreadQueueEvent", "Tcl_TraceCommand", "Tcl_TraceVar", "Tcl_TraceVar2",
  1635. "Tcl_TransferResult", "Tcl_TranslateFileName", "Tcl_TruncateChannel", "Tcl_Ungets", "Tcl_UniChar",
  1636. "Tcl_UniCharAtIndex", "Tcl_UniCharCaseMatch", "Tcl_UniCharIsAlnum", "Tcl_UniCharIsAlpha",
  1637. "Tcl_UniCharIsControl", "Tcl_UniCharIsDigit", "Tcl_UniCharIsGraph", "Tcl_UniCharIsLower",
  1638. "Tcl_UniCharIsPrint", "Tcl_UniCharIsPunct", "Tcl_UniCharIsSpace", "Tcl_UniCharIsUpper",
  1639. "Tcl_UniCharIsWordChar", "Tcl_UniCharLen", "Tcl_UniCharNcasecmp", "Tcl_UniCharNcmp", "Tcl_UniCharToLower",
  1640. "Tcl_UniCharToTitle", "Tcl_UniCharToUpper", "Tcl_UniCharToUtf", "Tcl_UniCharToUtfDString", "Tcl_UnlinkVar",
  1641. "Tcl_UnregisterChannel", "Tcl_UnsetVar", "Tcl_UnsetVar2", "Tcl_UnstackChannel", "Tcl_UntraceCommand",
  1642. "Tcl_UntraceVar", "Tcl_UntraceVar2", "Tcl_UpdateLinkedVar", "Tcl_UpVar", "Tcl_UpVar2", "Tcl_UtfAtIndex",
  1643. "Tcl_UtfBackslash", "Tcl_UtfCharComplete", "Tcl_UtfFindFirst", "Tcl_UtfFindLast", "Tcl_UtfNext",
  1644. "Tcl_UtfPrev", "Tcl_UtfToExternal", "Tcl_UtfToExternalDString", "Tcl_UtfToLower", "Tcl_UtfToTitle",
  1645. "Tcl_UtfToUniChar", "Tcl_UtfToUniCharDString", "Tcl_UtfToUpper", "Tcl_ValidateAllMemory", "Tcl_VarEval",
  1646. "Tcl_VarEvalVA", "Tcl_VarTraceInfo", "Tcl_VarTraceInfo2", "Tcl_WaitForEvent", "Tcl_WaitPid",
  1647. "Tcl_WinTCharToUtf", "Tcl_WinUtfToTChar", "Tcl_Write", "Tcl_WriteChars", "Tcl_WriteObj", "Tcl_WriteRaw",
  1648. "Tcl_WrongNumArgs", "Tcl_ZlibAdler32", "Tcl_ZlibCRC32", "Tcl_ZlibDeflate", "Tcl_ZlibInflate",
  1649. "Tcl_ZlibStreamChecksum", "Tcl_ZlibStreamClose", "Tcl_ZlibStreamEof", "Tcl_ZlibStreamGet",
  1650. "Tcl_ZlibStreamGetCommandName", "Tcl_ZlibStreamInit", "Tcl_ZlibStreamPut", "dde", "http", "msgcat",
  1651. "registry", "tcltest", "Tcl_AllocHashEntryProc", "Tcl_AppInitProc", "Tcl_ArgvInfo", "Tcl_AsyncProc",
  1652. "Tcl_ChannelProc", "Tcl_ChannelType", "Tcl_CloneProc", "Tcl_CloseProc", "Tcl_CmdDeleteProc", "Tcl_CmdInfo",
  1653. "Tcl_CmdObjTraceDeleteProc", "Tcl_CmdObjTraceProc", "Tcl_CmdProc", "Tcl_CmdTraceProc",
  1654. "Tcl_CommandTraceProc", "Tcl_CompareHashKeysProc", "Tcl_Config", "Tcl_DriverBlockModeProc",
  1655. "Tcl_DriverClose2Proc", "Tcl_DriverCloseProc", "Tcl_DriverFlushProc", "Tcl_DriverGetHandleProc",
  1656. "Tcl_DriverGetOptionProc", "Tcl_DriverHandlerProc", "Tcl_DriverInputProc", "Tcl_DriverOutputProc",
  1657. "Tcl_DriverSeekProc", "Tcl_DriverSetOptionProc", "Tcl_DriverThreadActionProc", "Tcl_DriverTruncateProc",
  1658. "Tcl_DriverWatchProc", "Tcl_DriverWideSeekProc", "Tcl_DupInternalRepProc", "Tcl_EncodingConvertProc",
  1659. "Tcl_EncodingFreeProc", "Tcl_EncodingType", "Tcl_Event", "Tcl_EventCheckProc", "Tcl_EventDeleteProc",
  1660. "Tcl_EventProc", "Tcl_EventSetupProc", "Tcl_ExitProc", "Tcl_FileProc", "Tcl_Filesystem",
  1661. "Tcl_FreeHashEntryProc", "Tcl_FreeInternalRepProc", "Tcl_FreeProc", "Tcl_FSAccessProc", "Tcl_FSChdirProc",
  1662. "Tcl_FSCopyDirectoryProc", "Tcl_FSCopyFileProc", "Tcl_FSCreateDirectoryProc", "Tcl_FSCreateInternalRepProc",
  1663. "Tcl_FSDeleteFileProc", "Tcl_FSDupInternalRepProc", "Tcl_FSFileAttrsGetProc", "Tcl_FSFileAttrsSetProc",
  1664. "Tcl_FSFilesystemPathTypeProc", "Tcl_FSFilesystemSeparatorProc", "Tcl_FSFreeInternalRepProc",
  1665. "Tcl_FSGetCwdProc", "Tcl_FSInternalToNormalizedProc", "Tcl_FSLinkProc", "Tcl_FSListVolumesProc",
  1666. "Tcl_FSLoadFileProc", "Tcl_FSLstatProc", "Tcl_FSMatchInDirectoryProc", "Tcl_FSNormalizePathProc",
  1667. "Tcl_FSOpenFileChannelProc", "Tcl_FSPathInFilesystemProc", "Tcl_FSRemoveDirectoryProc",
  1668. "Tcl_FSRenameFileProc", "Tcl_FSStatProc", "Tcl_FSUnloadFileProc", "Tcl_FSUtimeProc", "Tcl_GlobTypeData",
  1669. "Tcl_HashKeyType", "Tcl_IdleProc", "Tcl_Interp", "Tcl_InterpDeleteProc", "Tcl_LimitHandlerDeleteProc",
  1670. "Tcl_LimitHandlerProc", "Tcl_MainLoopProc", "Tcl_MathProc", "Tcl_MethodCallProc", "Tcl_MethodDeleteProc",
  1671. "Tcl_MethodType", "Tcl_NamespaceDeleteProc", "Tcl_NotifierProcs", "Tcl_Obj", "Tcl_ObjCmdProc",
  1672. "Tcl_ObjectMapMethodNameProc", "Tcl_ObjectMetadataDeleteProc", "Tcl_ObjType", "Tcl_PackageInitProc",
  1673. "Tcl_PackageUnloadProc", "Tcl_PanicProc", "Tcl_RegExpIndices", "Tcl_RegExpInfo", "Tcl_ScaleTimeProc",
  1674. "Tcl_SetFromAnyProc", "Tcl_TcpAcceptProc", "Tcl_Time", "Tcl_TimerProc", "Tcl_Token", "Tcl_UpdateStringProc",
  1675. "Tcl_Value", "Tcl_VarTraceProc", "argc", "argv", "argv0", "auto_path", "env", "errorCode", "errorInfo",
  1676. "filename", "re_syntax", "safe", "Tcl", "tcl_interactive", "tcl_library", "TCL_MEM_DEBUG",
  1677. "tcl_nonwordchars", "tcl_patchLevel", "tcl_pkgPath", "tcl_platform", "tcl_precision", "tcl_rcFileName",
  1678. "tcl_traceCompile", "tcl_traceEval", "tcl_version", "tcl_wordchars"
  1679. ]
  1680. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1681. # ###########################################
  1682. # ########### Shell SETUP ###################
  1683. # ###########################################
  1684. self.shell = FCShell(self, version=self.version)
  1685. self.shell._edit.set_model_data(self.myKeywords)
  1686. self.ui.code_editor.set_model_data(self.myKeywords)
  1687. self.shell.setWindowIcon(self.ui.app_icon)
  1688. self.shell.setWindowTitle("FlatCAM Shell")
  1689. self.shell.resize(*self.defaults["global_shell_shape"])
  1690. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1691. self.shell.append_output(_("(Type help to get started)\n\n"))
  1692. self.init_tcl()
  1693. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1694. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1695. self.ui.shell_dock.setWidget(self.shell)
  1696. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1697. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1698. QtWidgets.QDockWidget.DockWidgetFloatable |
  1699. QtWidgets.QDockWidget.DockWidgetClosable)
  1700. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1701. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1702. if self.defaults["global_shell_at_startup"]:
  1703. self.ui.shell_dock.show()
  1704. else:
  1705. self.ui.shell_dock.hide()
  1706. # ###########################################
  1707. # ######### Tools and Plugins ###############
  1708. # ###########################################
  1709. self.dblsidedtool = None
  1710. self.measurement_tool = None
  1711. self.panelize_tool = None
  1712. self.film_tool = None
  1713. self.paste_tool = None
  1714. self.calculator_tool = None
  1715. self.sub_tool = None
  1716. self.move_tool = None
  1717. self.cutout_tool = None
  1718. self.ncclear_tool = None
  1719. self.paint_tool = None
  1720. self.transform_tool = None
  1721. self.properties_tool = None
  1722. self.pdf_tool = None
  1723. self.image_tool = None
  1724. self.pcb_wizard_tool = None
  1725. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1726. self.install_tools()
  1727. # ### System Font Parsing ###
  1728. # self.f_parse = ParseFont(self)
  1729. # self.parse_system_fonts()
  1730. # ###############################################
  1731. # ######## START-UP ARGUMENTS ###################
  1732. # ###############################################
  1733. # test if the program was started with a script as parameter
  1734. if self.cmd_line_shellfile:
  1735. try:
  1736. with open(self.cmd_line_shellfile, "r") as myfile:
  1737. cmd_line_shellfile_text = myfile.read()
  1738. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1739. except Exception as ext:
  1740. print("ERROR: ", ext)
  1741. sys.exit(2)
  1742. # ###############################################
  1743. # ############# Check for updates ###############
  1744. # ###############################################
  1745. # Separate thread (Not worker)
  1746. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1747. if (self.beta is False or self.beta is None) and \
  1748. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1749. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1750. self.thr2 = QtCore.QThread()
  1751. self.worker_task.emit({'fcn': self.version_check,
  1752. 'params': []})
  1753. self.thr2.start(QtCore.QThread.LowPriority)
  1754. # ################################################
  1755. # ######### Variables for global usage ###########
  1756. # ################################################
  1757. # coordinates for relative position display
  1758. self.rel_point1 = (0, 0)
  1759. self.rel_point2 = (0, 0)
  1760. # variable to store coordinates
  1761. self.pos = (0, 0)
  1762. self.pos_jump = (0, 0)
  1763. # decide if we have a double click or single click
  1764. self.doubleclick = False
  1765. # variable to store if a command is active (then the var is not None) and which one it is
  1766. self.command_active = None
  1767. # variable to store the status of moving selection action
  1768. # None value means that it's not an selection action
  1769. # True value = a selection from left to right
  1770. # False value = a selection from right to left
  1771. self.selection_type = None
  1772. # List to store the objects that are currently loaded in FlatCAM
  1773. # This list is updated on each object creation or object delete
  1774. self.all_objects_list = []
  1775. # List to store the objects that are selected
  1776. self.sel_objects_list = []
  1777. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1778. self.key_modifiers = None
  1779. # Variable to hold the status of the axis
  1780. self.toggle_axis = True
  1781. # Variable to store the status of the fullscreen event
  1782. self.toggle_fscreen = False
  1783. # Variable to store the status of the code editor
  1784. self.toggle_codeeditor = False
  1785. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1786. self.click_noproject = False
  1787. self.cursor = None
  1788. # Variable to store the GCODE that was edited
  1789. self.gcode_edited = ""
  1790. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1791. self.preferences_changed_flag = False
  1792. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1793. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1794. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1795. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1796. ]
  1797. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1798. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1799. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1800. 'mpf'
  1801. ]
  1802. self.svg_list = ['svg']
  1803. self.dxf_list = ['dxf']
  1804. self.pdf_list = ['pdf']
  1805. self.prj_list = ['flatprj']
  1806. self.conf_list = ['flatconfig']
  1807. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1808. # flag for polygons not cleared
  1809. self.poly_not_cleared = False
  1810. # VisPy visuals
  1811. self.isHovering = False
  1812. self.notHovering = True
  1813. # #########################################################
  1814. # ### Save defaults to factory_defaults.FlatConfig file ###
  1815. # ### It's done only once after install ###################
  1816. # #########################################################
  1817. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1818. fac_def_from_file = factory_file.read()
  1819. factory_defaults = json.loads(fac_def_from_file)
  1820. # if the file contain an empty dictionary then save the factory defaults into the file
  1821. if not factory_defaults:
  1822. self.save_factory_defaults(silent=False)
  1823. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1824. initial_lay = 'compact'
  1825. self.on_layout(lay=initial_lay)
  1826. # Set the combobox in Preferences to the current layout
  1827. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1828. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1829. factory_file.close()
  1830. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1831. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1832. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1833. ####################################################
  1834. # ### ADDING FlatCAM EDITORS section ###############
  1835. ####################################################
  1836. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1837. # at the first launch of the App , the editors will not be functional.
  1838. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1839. self.exc_editor = FlatCAMExcEditor(self)
  1840. self.grb_editor = FlatCAMGrbEditor(self)
  1841. self.log.debug("Finished adding FlatCAM Editor's.")
  1842. # Post-GUI initialization: Experimental attempt
  1843. # to perform unit tests on the GUI.
  1844. # if post_gui is not None:
  1845. # post_gui(self)
  1846. App.log.debug("END of constructor. Releasing control.")
  1847. self.set_ui_title(name=_("New Project - Not saved"))
  1848. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1849. # the path/file_name must be enclosed in quotes if it contain spaces
  1850. if App.args:
  1851. self.args_at_startup.emit()
  1852. @staticmethod
  1853. def copy_and_overwrite(from_path, to_path):
  1854. """
  1855. From here:
  1856. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1857. :param from_path: source path
  1858. :param to_path: destination path
  1859. :return: None
  1860. """
  1861. if os.path.exists(to_path):
  1862. shutil.rmtree(to_path)
  1863. try:
  1864. shutil.copytree(from_path, to_path)
  1865. except FileNotFoundError:
  1866. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1867. shutil.copytree(from_new_path, to_path)
  1868. def on_startup_args(self):
  1869. log.debug("Application was started with an argument. Processing ...")
  1870. for argument in App.args:
  1871. if '.FlatPrj' in argument:
  1872. try:
  1873. project_name = str(argument)
  1874. if project_name == "":
  1875. self.inform.emit(_("Open cancelled."))
  1876. else:
  1877. # self.open_project(project_name)
  1878. run_from_arg = True
  1879. # self.worker_task.emit({'fcn': self.open_project,
  1880. # 'params': [project_name, run_from_arg]})
  1881. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1882. except Exception as e:
  1883. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1884. elif '.FlatConfig' in argument:
  1885. try:
  1886. file_name = str(argument)
  1887. if file_name == "":
  1888. self.inform.emit(_("Open Config file failed."))
  1889. else:
  1890. # run_from_arg = True
  1891. # self.worker_task.emit({'fcn': self.open_config_file,
  1892. # 'params': [file_name, run_from_arg]})
  1893. self.open_config_file(file_name, run_from_arg=True)
  1894. except Exception as e:
  1895. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1896. elif '.FlatScript' in argument:
  1897. try:
  1898. file_name = str(argument)
  1899. if file_name == "":
  1900. self.inform.emit(_("Open Script file failed."))
  1901. else:
  1902. # run_from_arg = True
  1903. # self.worker_task.emit({'fcn': self.open_script_file,
  1904. # 'params': [file_name, run_from_arg]})
  1905. self.on_filerunscript(name=file_name)
  1906. except Exception as e:
  1907. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1908. def set_ui_title(self, name):
  1909. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  1910. (self.version,
  1911. ('BETA' if self.beta else ''),
  1912. platform.architecture()[0],
  1913. name)
  1914. )
  1915. def defaults_read_form(self):
  1916. for option in self.defaults_form_fields:
  1917. try:
  1918. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1919. except Exception as e:
  1920. log.debug("App.defaults_read_form() --> %s" % str(e))
  1921. def defaults_write_form(self, factor=None, fl_units=None):
  1922. for option in self.defaults:
  1923. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  1924. # try:
  1925. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1926. # except KeyError:
  1927. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1928. # # TODO: Rethink this?
  1929. # pass
  1930. def defaults_write_form_field(self, field, factor=None, units=None):
  1931. try:
  1932. if factor is None:
  1933. if units is None:
  1934. self.defaults_form_fields[field].set_value(self.defaults[field])
  1935. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  1936. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  1937. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  1938. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  1939. else:
  1940. if units is None:
  1941. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1942. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  1943. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  1944. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  1945. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  1946. except KeyError:
  1947. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  1948. # TODO: Rethink this?
  1949. pass
  1950. except AttributeError:
  1951. log.debug(field)
  1952. def clear_pool(self):
  1953. self.pool.close()
  1954. self.pool = Pool()
  1955. self.pool_recreated.emit(self.pool)
  1956. gc.collect()
  1957. # the order that the tools are installed is important as they can depend on each other install position
  1958. def install_tools(self):
  1959. self.dblsidedtool = DblSidedTool(self)
  1960. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1961. self.measurement_tool = Measurement(self)
  1962. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1963. self.panelize_tool = Panelize(self)
  1964. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1965. self.film_tool = Film(self)
  1966. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1967. self.paste_tool = SolderPaste(self)
  1968. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  1969. self.calculator_tool = ToolCalculator(self)
  1970. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  1971. self.sub_tool = ToolSub(self)
  1972. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  1973. self.move_tool = ToolMove(self)
  1974. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1975. before=self.ui.menueditorigin)
  1976. self.cutout_tool = CutOut(self)
  1977. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1978. before=self.measurement_tool.menuAction)
  1979. self.ncclear_tool = NonCopperClear(self)
  1980. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1981. before=self.measurement_tool.menuAction, separator=True)
  1982. self.paint_tool = ToolPaint(self)
  1983. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1984. before=self.measurement_tool.menuAction, separator=True)
  1985. self.transform_tool = ToolTransform(self)
  1986. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1987. self.properties_tool = Properties(self)
  1988. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1989. self.pdf_tool = ToolPDF(self)
  1990. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  1991. separator=True)
  1992. self.image_tool = ToolImage(self)
  1993. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1994. separator=True)
  1995. self.pcb_wizard_tool = PcbWizard(self)
  1996. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  1997. self.log.debug("Tools are installed.")
  1998. def remove_tools(self):
  1999. for act in self.ui.menutool.actions():
  2000. self.ui.menutool.removeAction(act)
  2001. def init_tools(self):
  2002. log.debug("init_tools()")
  2003. # delete the data currently in the Tools Tab and the Tab itself
  2004. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2005. if widget is not None:
  2006. widget.deleteLater()
  2007. self.ui.notebook.removeTab(2)
  2008. # rebuild the Tools Tab
  2009. self.ui.tool_tab = QtWidgets.QWidget()
  2010. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2011. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2012. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2013. self.ui.tool_scroll_area = VerticalScrollArea()
  2014. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2015. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2016. # first remove all of them
  2017. self.remove_tools()
  2018. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2019. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2020. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2021. # third install all of them
  2022. self.install_tools()
  2023. self.log.debug("Tools are initialized.")
  2024. # def parse_system_fonts(self):
  2025. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2026. # 'params': []})
  2027. def connect_toolbar_signals(self):
  2028. # Toolbar
  2029. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2030. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2031. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2032. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2033. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2034. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2035. self.ui.replot_btn.triggered.connect(self.plot_all)
  2036. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2037. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2038. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2039. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2040. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2041. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2042. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2043. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2044. self.ui.delete_btn.triggered.connect(self.on_delete)
  2045. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2046. # Tools Toolbar Signals
  2047. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2048. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2049. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2050. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2051. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2052. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2053. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2054. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2055. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2056. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2057. def object2editor(self):
  2058. """
  2059. Send the current Geometry or Excellon object (if any) into the editor.
  2060. :return: None
  2061. """
  2062. self.report_usage("object2editor()")
  2063. edited_object = self.collection.get_active()
  2064. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2065. isinstance(edited_object, FlatCAMExcellon):
  2066. pass
  2067. else:
  2068. self.inform.emit(_("[WARNING_NOTCL] Select a Geometry, Gerber or Excellon Object to edit."))
  2069. return
  2070. if isinstance(edited_object, FlatCAMGeometry):
  2071. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2072. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2073. # we set the notebook to hidden
  2074. self.ui.splitter.setSizes([0, 1])
  2075. if edited_object.multigeo is True:
  2076. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2077. if len(edited_tools) > 1:
  2078. self.inform.emit(_("[WARNING_NOTCL] Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2079. "is not possible.\n"
  2080. "Edit only one geometry at a time."))
  2081. # determine the tool dia of the selected tool
  2082. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2083. # now find the key in the edited_object.tools that has this tooldia
  2084. multi_tool = 1
  2085. for tool in edited_object.tools:
  2086. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2087. multi_tool = tool
  2088. break
  2089. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2090. else:
  2091. self.geo_editor.edit_fcgeometry(edited_object)
  2092. # set call source to the Editor we go into
  2093. self.call_source = 'geo_editor'
  2094. elif isinstance(edited_object, FlatCAMExcellon):
  2095. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2096. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2097. if self.ui.splitter.sizes()[0] == 0:
  2098. self.ui.splitter.setSizes([1, 1])
  2099. self.exc_editor.edit_fcexcellon(edited_object)
  2100. # set call source to the Editor we go into
  2101. self.call_source = 'exc_editor'
  2102. elif isinstance(edited_object, FlatCAMGerber):
  2103. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2104. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2105. if self.ui.splitter.sizes()[0] == 0:
  2106. self.ui.splitter.setSizes([1, 1])
  2107. self.grb_editor.edit_fcgerber(edited_object)
  2108. # set call source to the Editor we go into
  2109. self.call_source = 'grb_editor'
  2110. # make sure that we can't select another object while in Editor Mode:
  2111. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2112. self.ui.project_frame.setDisabled(True)
  2113. # delete any selection shape that might be active as they are not relevant in Editor
  2114. self.delete_selection_shape()
  2115. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2116. self.ui.plot_tab_area.protectTab(0)
  2117. self.inform.emit(_("[WARNING_NOTCL] Editor is activated ..."))
  2118. self.should_we_save = True
  2119. def editor2object(self, cleanup=None):
  2120. """
  2121. Transfers the Geometry or Excellon from the editor to the current object.
  2122. :return: None
  2123. """
  2124. self.report_usage("editor2object()")
  2125. # do not update a geometry or excellon object unless it comes out of an editor
  2126. if self.call_source != 'app':
  2127. edited_obj = self.collection.get_active()
  2128. if cleanup is None:
  2129. msgbox = QtWidgets.QMessageBox()
  2130. msgbox.setText(_("Do you want to save the edited object?"))
  2131. msgbox.setWindowTitle(_("Close Editor"))
  2132. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2133. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2134. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2135. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2136. msgbox.setDefaultButton(bt_yes)
  2137. msgbox.exec_()
  2138. response = msgbox.clickedButton()
  2139. if response == bt_yes:
  2140. # clean the Tools Tab
  2141. self.ui.tool_scroll_area.takeWidget()
  2142. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2143. self.ui.notebook.setTabText(2, "Tool")
  2144. if isinstance(edited_obj, FlatCAMGeometry):
  2145. obj_type = "Geometry"
  2146. if cleanup is None:
  2147. self.geo_editor.update_fcgeometry(edited_obj)
  2148. self.geo_editor.update_options(edited_obj)
  2149. self.geo_editor.deactivate()
  2150. # update the geo object options so it is including the bounding box values
  2151. try:
  2152. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2153. edited_obj.options['xmin'] = xmin
  2154. edited_obj.options['ymin'] = ymin
  2155. edited_obj.options['xmax'] = xmax
  2156. edited_obj.options['ymax'] = ymax
  2157. except AttributeError as e:
  2158. self.inform.emit(_("[WARNING] Object empty after edit."))
  2159. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2160. elif isinstance(edited_obj, FlatCAMGerber):
  2161. obj_type = "Gerber"
  2162. if cleanup is None:
  2163. self.grb_editor.update_fcgerber()
  2164. self.grb_editor.update_options(edited_obj)
  2165. self.grb_editor.deactivate_grb_editor()
  2166. # delete the old object (the source object) if it was an empty one
  2167. if len(edited_obj.solid_geometry) == 0:
  2168. old_name = edited_obj.options['name']
  2169. self.collection.set_active(old_name)
  2170. self.collection.delete_active()
  2171. elif isinstance(edited_obj, FlatCAMExcellon):
  2172. obj_type = "Excellon"
  2173. if cleanup is None:
  2174. self.exc_editor.update_fcexcellon(edited_obj)
  2175. self.exc_editor.update_options(edited_obj)
  2176. self.exc_editor.deactivate()
  2177. else:
  2178. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2179. return
  2180. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  2181. elif response == bt_no:
  2182. # clean the Tools Tab
  2183. self.ui.tool_scroll_area.takeWidget()
  2184. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2185. self.ui.notebook.setTabText(2, "Tool")
  2186. if isinstance(edited_obj, FlatCAMGeometry):
  2187. self.geo_editor.deactivate()
  2188. elif isinstance(edited_obj, FlatCAMGerber):
  2189. self.grb_editor.deactivate_grb_editor()
  2190. elif isinstance(edited_obj, FlatCAMExcellon):
  2191. self.exc_editor.deactivate()
  2192. # set focus on the project tab
  2193. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2194. else:
  2195. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2196. return
  2197. elif response == bt_cancel:
  2198. return
  2199. else:
  2200. if isinstance(edited_obj, FlatCAMGeometry):
  2201. self.geo_editor.deactivate()
  2202. elif isinstance(edited_obj, FlatCAMGerber):
  2203. self.grb_editor.deactivate_grb_editor()
  2204. elif isinstance(edited_obj, FlatCAMExcellon):
  2205. self.exc_editor.deactivate()
  2206. else:
  2207. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2208. return
  2209. # if notebook is hidden we show it
  2210. if self.ui.splitter.sizes()[0] == 0:
  2211. self.ui.splitter.setSizes([1, 1])
  2212. # restore the call_source to app
  2213. self.call_source = 'app'
  2214. edited_obj.plot()
  2215. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2216. self.ui.plot_tab_area.protectTab(0)
  2217. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2218. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2219. self.ui.project_frame.setDisabled(False)
  2220. def get_last_folder(self):
  2221. return self.defaults["global_last_folder"]
  2222. def get_last_save_folder(self):
  2223. loc = self.defaults["global_last_save_folder"]
  2224. if loc is None:
  2225. loc = self.defaults["global_last_folder"]
  2226. if loc is None:
  2227. loc = os.path.dirname(__file__)
  2228. return loc
  2229. def report_usage(self, resource):
  2230. """
  2231. Increments usage counter for the given resource
  2232. in self.defaults['global_stats'].
  2233. :param resource: Name of the resource.
  2234. :return: None
  2235. """
  2236. if resource in self.defaults['global_stats']:
  2237. self.defaults['global_stats'][resource] += 1
  2238. else:
  2239. self.defaults['global_stats'][resource] = 1
  2240. def init_tcl(self):
  2241. if hasattr(self, 'tcl'):
  2242. # self.tcl = None
  2243. # TODO we need to clean non default variables and procedures here
  2244. # new object cannot be used here as it will not remember values created for next passes,
  2245. # because tcl was execudted in old instance of TCL
  2246. pass
  2247. else:
  2248. self.tcl = tk.Tcl()
  2249. self.setup_shell()
  2250. self.log.debug("TCL Shell has been initialized.")
  2251. # TODO: This shouldn't be here.
  2252. class TclErrorException(Exception):
  2253. """
  2254. this exception is defined here, to be able catch it if we ssuccessfully handle all errors from shell command
  2255. """
  2256. pass
  2257. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2258. """
  2259. Shows a message on the FlatCAM Shell
  2260. :param msg: Message to display.
  2261. :param show: Opens the shell.
  2262. :param error: Shows the message as an error.
  2263. :param warning: Shows the message as an warning.
  2264. :param success: Shows the message as an success.
  2265. :param selected: Indicate that something was selected on canvas
  2266. :return: None
  2267. """
  2268. if show:
  2269. self.ui.shell_dock.show()
  2270. try:
  2271. if error:
  2272. self.shell.append_error(msg + "\n")
  2273. elif warning:
  2274. self.shell.append_warning(msg + "\n")
  2275. elif success:
  2276. self.shell.append_success(msg + "\n")
  2277. elif selected:
  2278. self.shell.append_selected(msg + "\n")
  2279. else:
  2280. self.shell.append_output(msg + "\n")
  2281. except AttributeError:
  2282. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2283. def raise_tcl_unknown_error(self, unknownException):
  2284. """
  2285. Raise exception if is different type than TclErrorException
  2286. this is here mainly to show unknown errors inside TCL shell console.
  2287. :param unknownException:
  2288. :return:
  2289. """
  2290. if not isinstance(unknownException, self.TclErrorException):
  2291. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2292. else:
  2293. raise unknownException
  2294. def display_tcl_error(self, error, error_info=None):
  2295. """
  2296. Escape bracket [ with '\' otherwise there is error
  2297. "ERROR: missing close-bracket" instead of real error
  2298. :param error: it may be text or exception
  2299. :param error_info: Some informations about the error
  2300. :return: None
  2301. """
  2302. if isinstance(error, Exception):
  2303. exc_type, exc_value, exc_traceback = error_info
  2304. if not isinstance(error, self.TclErrorException):
  2305. show_trace = 1
  2306. else:
  2307. show_trace = int(self.defaults['global_verbose_error_level'])
  2308. if show_trace > 0:
  2309. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2310. trc_formated = []
  2311. for a in reversed(trc):
  2312. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2313. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2314. else:
  2315. text = "%s" % error
  2316. else:
  2317. text = error
  2318. text = text.replace('[', '\\[').replace('"', '\\"')
  2319. self.tcl.eval('return -code error "%s"' % text)
  2320. def raise_tcl_error(self, text):
  2321. """
  2322. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2323. :param text: text of error
  2324. :return: raise exception
  2325. """
  2326. self.display_tcl_error(text)
  2327. raise self.TclErrorException(text)
  2328. def exec_command(self, text):
  2329. """
  2330. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2331. Also handles execution in separated threads
  2332. :param text:
  2333. :return: output if there was any
  2334. """
  2335. self.report_usage('exec_command')
  2336. result = self.exec_command_test(text, False)
  2337. # MS: added this method call so the geometry is updated once the TCL command is executed
  2338. self.plot_all()
  2339. return result
  2340. def exec_command_test(self, text, reraise=True):
  2341. """
  2342. Same as exec_command(...) with additional control over exceptions.
  2343. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2344. :param text: Input command
  2345. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2346. :return: Output from the command
  2347. """
  2348. text = str(text)
  2349. try:
  2350. self.shell.open_proccessing() # Disables input box.
  2351. result = self.tcl.eval(str(text))
  2352. if result != 'None':
  2353. self.shell.append_output(result + '\n')
  2354. except tk.TclError as e:
  2355. # This will display more precise answer if something in TCL shell fails
  2356. result = self.tcl.eval("set errorInfo")
  2357. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2358. self.shell.append_error('ERROR: ' + result + '\n')
  2359. # Show error in console and just return or in test raise exception
  2360. if reraise:
  2361. raise e
  2362. finally:
  2363. self.shell.close_proccessing()
  2364. pass
  2365. return result
  2366. # """
  2367. # Code below is unsused. Saved for later.
  2368. # """
  2369. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2370. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2371. # self.log.debug(parts)
  2372. # try:
  2373. # if parts[0] not in commands:
  2374. # self.shell.append_error("Unknown command\n")
  2375. # return
  2376. #
  2377. # #import inspect
  2378. # #inspect.getargspec(someMethod)
  2379. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2380. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2381. # self.shell.append_error(
  2382. # "Command %s takes %d arguments. %d given.\n" %
  2383. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2384. # )
  2385. # return
  2386. #
  2387. # cmdfcn = commands[parts[0]]["fcn"]
  2388. # cmdconv = commands[parts[0]]["converters"]
  2389. # if len(parts) - 1 > 0:
  2390. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2391. # else:
  2392. # retval = cmdfcn()
  2393. # retfcn = commands[parts[0]]["retfcn"]
  2394. # if retval and retfcn(retval):
  2395. # self.shell.append_output(retfcn(retval) + "\n")
  2396. #
  2397. # except Exception as e:
  2398. # #self.shell.append_error(''.join(traceback.format_exc()))
  2399. # #self.shell.append_error("?\n")
  2400. # self.shell.append_error(str(e) + "\n")
  2401. def info(self, msg):
  2402. """
  2403. Informs the user. Normally on the status bar, optionally
  2404. also on the shell.
  2405. :param msg: Text to write.
  2406. :return: None
  2407. """
  2408. # Type of message in brackets at the beginning of the message.
  2409. match = re.search("\[([^\]]+)\](.*)", msg)
  2410. if match:
  2411. level = match.group(1)
  2412. msg_ = match.group(2)
  2413. self.ui.fcinfo.set_status(str(msg_), level=level)
  2414. if level.lower() == "error":
  2415. self.shell_message(msg, error=True, show=True)
  2416. elif level.lower() == "warning":
  2417. self.shell_message(msg, warning=True, show=True)
  2418. elif level.lower() == "error_notcl":
  2419. self.shell_message(msg, error=True, show=False)
  2420. elif level.lower() == "warning_notcl":
  2421. self.shell_message(msg, warning=True, show=False)
  2422. elif level.lower() == "success":
  2423. self.shell_message(msg, success=True, show=False)
  2424. elif level.lower() == "selected":
  2425. self.shell_message(msg, selected=True, show=False)
  2426. else:
  2427. self.shell_message(msg, show=False)
  2428. else:
  2429. self.ui.fcinfo.set_status(str(msg), level="info")
  2430. # make sure that if the message is to clear the infobar with a space
  2431. # is not printed over and over on the shell
  2432. if msg != '':
  2433. self.shell_message(msg)
  2434. def restore_toolbar_view(self):
  2435. tb = self.defaults["global_toolbar_view"]
  2436. if tb & 1:
  2437. self.ui.toolbarfile.setVisible(True)
  2438. else:
  2439. self.ui.toolbarfile.setVisible(False)
  2440. if tb & 2:
  2441. self.ui.toolbargeo.setVisible(True)
  2442. else:
  2443. self.ui.toolbargeo.setVisible(False)
  2444. if tb & 4:
  2445. self.ui.toolbarview.setVisible(True)
  2446. else:
  2447. self.ui.toolbarview.setVisible(False)
  2448. if tb & 8:
  2449. self.ui.toolbartools.setVisible(True)
  2450. else:
  2451. self.ui.toolbartools.setVisible(False)
  2452. if tb & 16:
  2453. self.ui.exc_edit_toolbar.setVisible(True)
  2454. else:
  2455. self.ui.exc_edit_toolbar.setVisible(False)
  2456. if tb & 32:
  2457. self.ui.geo_edit_toolbar.setVisible(True)
  2458. else:
  2459. self.ui.geo_edit_toolbar.setVisible(False)
  2460. if tb & 64:
  2461. self.ui.grb_edit_toolbar.setVisible(True)
  2462. else:
  2463. self.ui.grb_edit_toolbar.setVisible(False)
  2464. if tb & 128:
  2465. self.ui.snap_toolbar.setVisible(True)
  2466. else:
  2467. self.ui.snap_toolbar.setVisible(False)
  2468. if tb & 256:
  2469. self.ui.toolbarshell.setVisible(True)
  2470. else:
  2471. self.ui.toolbarshell.setVisible(False)
  2472. def load_defaults(self, filename):
  2473. """
  2474. Loads the aplication's default settings from current_defaults.FlatConfig into
  2475. ``self.defaults``.
  2476. :return: None
  2477. """
  2478. try:
  2479. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2480. options = f.read()
  2481. f.close()
  2482. except IOError:
  2483. self.log.error("Could not load defaults file.")
  2484. self.inform.emit(_("[ERROR] Could not load defaults file."))
  2485. # in case the defaults file can't be loaded, show all toolbars
  2486. self.defaults["global_toolbar_view"] = 511
  2487. return
  2488. try:
  2489. defaults = json.loads(options)
  2490. except:
  2491. # in case the defaults file can't be loaded, show all toolbars
  2492. self.defaults["global_toolbar_view"] = 511
  2493. e = sys.exc_info()[0]
  2494. App.log.error(str(e))
  2495. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  2496. return
  2497. self.defaults.update(defaults)
  2498. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2499. # restore the toolbar view
  2500. self.restore_toolbar_view()
  2501. def on_import_preferences(self):
  2502. """
  2503. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2504. ``self.defaults``.
  2505. :return: None
  2506. """
  2507. self.report_usage("on_import_preferences")
  2508. App.log.debug("on_import_preferences()")
  2509. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2510. try:
  2511. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2512. directory=self.data_path,
  2513. filter=filter_)
  2514. except TypeError:
  2515. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2516. filter=filter_)
  2517. filename = str(filename)
  2518. if filename == "":
  2519. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences import cancelled."))
  2520. else:
  2521. try:
  2522. f = open(filename)
  2523. options = f.read()
  2524. f.close()
  2525. except IOError:
  2526. self.log.error("Could not load defaults file.")
  2527. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2528. return
  2529. try:
  2530. defaults_from_file = json.loads(options)
  2531. except Exception as e:
  2532. e = sys.exc_info()[0]
  2533. App.log.error(str(e))
  2534. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2535. return
  2536. self.defaults.update(defaults_from_file)
  2537. self.on_preferences_edited()
  2538. self.inform.emit(_("[success] Imported Defaults from %s") % filename)
  2539. def on_export_preferences(self):
  2540. self.report_usage("on_export_preferences")
  2541. App.log.debug("on_export_preferences()")
  2542. defaults_file_content = None
  2543. self.date = str(datetime.today()).rpartition('.')[0]
  2544. self.date = ''.join(c for c in self.date if c not in ':-')
  2545. self.date = self.date.replace(' ', '_')
  2546. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2547. try:
  2548. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2549. caption=_("Export FlatCAM Preferences"),
  2550. directory=self.data_path + '/preferences_' + self.date,
  2551. filter=filter__
  2552. )
  2553. except TypeError:
  2554. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2555. filter=filter__)
  2556. filename = str(filename)
  2557. defaults_from_file = {}
  2558. if filename == "":
  2559. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences export cancelled."))
  2560. return
  2561. else:
  2562. try:
  2563. f = open(filename, 'w')
  2564. defaults_file_content = f.read()
  2565. f.close()
  2566. except PermissionError:
  2567. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  2568. "Most likely another app is holding the file open and not accessible."))
  2569. return
  2570. except IOError:
  2571. App.log.debug('Creating a new preferences file ...')
  2572. f = open(filename, 'w')
  2573. json.dump({}, f)
  2574. f.close()
  2575. except:
  2576. e = sys.exc_info()[0]
  2577. App.log.error("Could not load defaults file.")
  2578. App.log.error(str(e))
  2579. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2580. return
  2581. try:
  2582. defaults_from_file = json.loads(defaults_file_content)
  2583. except:
  2584. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2585. # Update options
  2586. self.defaults_read_form()
  2587. defaults_from_file.update(self.defaults)
  2588. self.propagate_defaults(silent=True)
  2589. # Save update options
  2590. try:
  2591. f = open(filename, "w")
  2592. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2593. f.close()
  2594. except:
  2595. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2596. return
  2597. if self.defaults["global_open_style"] is False:
  2598. self.file_opened.emit("preferences", filename)
  2599. self.file_saved.emit("preferences", filename)
  2600. self.inform.emit("[success] Exported Defaults to %s" % filename)
  2601. def on_preferences_open_folder(self):
  2602. self.report_usage("on_preferences_open_folder()")
  2603. if sys.platform == 'win32':
  2604. subprocess.Popen('explorer %s' % self.data_path)
  2605. elif sys.platform == 'darwin':
  2606. os.system('open "%s"' % self.data_path)
  2607. else:
  2608. subprocess.Popen(['xdg-open', self.data_path])
  2609. self.inform.emit("[success] FlatCAM Preferences Folder opened.")
  2610. def save_geometry(self, x, y, width, height, notebook_width):
  2611. self.defaults["global_def_win_x"] = x
  2612. self.defaults["global_def_win_y"] = y
  2613. self.defaults["global_def_win_w"] = width
  2614. self.defaults["global_def_win_h"] = height
  2615. self.defaults["global_def_notebook_width"] = notebook_width
  2616. self.save_defaults()
  2617. def message_dialog(self, title, message, kind="info"):
  2618. icon = {"info": QtWidgets.QMessageBox.Information,
  2619. "warning": QtWidgets.QMessageBox.Warning,
  2620. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2621. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2622. dlg.setText(message)
  2623. dlg.exec_()
  2624. def register_recent(self, kind, filename):
  2625. self.log.debug("register_recent()")
  2626. self.log.debug(" %s" % kind)
  2627. self.log.debug(" %s" % filename)
  2628. record = {'kind': str(kind), 'filename': str(filename)}
  2629. if record in self.recent:
  2630. return
  2631. if record in self.recent_projects:
  2632. return
  2633. if record['kind'] == 'project':
  2634. self.recent_projects.insert(0, record)
  2635. else:
  2636. self.recent.insert(0, record)
  2637. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2638. self.recent.pop()
  2639. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2640. self.recent_projects.pop()
  2641. try:
  2642. f = open(self.data_path + '/recent.json', 'w')
  2643. except IOError:
  2644. App.log.error("Failed to open recent items file for writing.")
  2645. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
  2646. return
  2647. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2648. f.close()
  2649. try:
  2650. fp = open(self.data_path + '/recent_projects.json', 'w')
  2651. except IOError:
  2652. App.log.error("Failed to open recent items file for writing.")
  2653. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent projects file for writing.'))
  2654. return
  2655. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2656. fp.close()
  2657. # Re-build the recent items menu
  2658. self.setup_recent_items()
  2659. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2660. """
  2661. Creates a new specialized FlatCAMObj and attaches it to the application,
  2662. this is, updates the GUI accordingly, any other records and plots it.
  2663. This method is thread-safe.
  2664. Notes:
  2665. * If the name is in use, the self.collection will modify it
  2666. when appending it to the collection. There is no need to handle
  2667. name conflicts here.
  2668. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2669. :type kind: str
  2670. :param name: Name for the object.
  2671. :type name: str
  2672. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2673. The function is called with 2 parameters: the new object and the App instance.
  2674. :type initialize: function
  2675. :param active:
  2676. :param fit:
  2677. :param plot: If to plot the resulting object
  2678. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2679. self.colleaction
  2680. :return: None
  2681. :rtype: None
  2682. """
  2683. App.log.debug("new_object()")
  2684. obj_plot = plot
  2685. obj_autoselected = autoselected
  2686. t0 = time.time() # Debug
  2687. # ## Create object
  2688. classdict = {
  2689. "gerber": FlatCAMGerber,
  2690. "excellon": FlatCAMExcellon,
  2691. "cncjob": FlatCAMCNCjob,
  2692. "geometry": FlatCAMGeometry
  2693. }
  2694. App.log.debug("Calling object constructor...")
  2695. obj = classdict[kind](name)
  2696. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2697. # Set options from "Project options" form
  2698. self.options_read_form()
  2699. # IMPORTANT
  2700. # The key names in defaults and options dictionary's are not random:
  2701. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2702. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2703. # the options from project options form into the self.options. After that, below, depending on the type of
  2704. # object that is created, it will strip the name of the object and the underline (if the original key was
  2705. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2706. # "toolchange"
  2707. for option in self.options:
  2708. if option.find(kind + "_") == 0:
  2709. oname = option[len(kind) + 1:]
  2710. obj.options[oname] = self.options[option]
  2711. obj.isHovering = False
  2712. obj.notHovering = True
  2713. # Initialize as per user request
  2714. # User must take care to implement initialize
  2715. # in a thread-safe way as is is likely that we
  2716. # have been invoked in a separate thread.
  2717. t1 = time.time()
  2718. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2719. try:
  2720. return_value = initialize(obj, self)
  2721. except Exception as e:
  2722. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2723. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2724. msg += traceback.format_exc()
  2725. self.inform.emit(msg)
  2726. # if str(e) == "Empty Geometry":
  2727. # self.inform.emit("[ERROR_NOTCL] )
  2728. # else:
  2729. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2730. return "fail"
  2731. t2 = time.time()
  2732. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2733. if return_value == 'fail':
  2734. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2735. return "fail"
  2736. # Check units and convert if necessary
  2737. # This condition CAN be true because initialize() can change obj.units
  2738. if self.options["units"].upper() != obj.units.upper():
  2739. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2740. obj.convert_units(self.options["units"])
  2741. t3 = time.time()
  2742. self.log.debug("%f seconds converting units." % (t3 - t2))
  2743. # Create the bounding box for the object and then add the results to the obj.options
  2744. try:
  2745. xmin, ymin, xmax, ymax = obj.bounds()
  2746. obj.options['xmin'] = xmin
  2747. obj.options['ymin'] = ymin
  2748. obj.options['xmax'] = xmax
  2749. obj.options['ymax'] = ymax
  2750. except Exception as e:
  2751. log.warning("The object has no bounds properties. %s" % str(e))
  2752. return "fail"
  2753. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2754. # Move the object to the main thread and let the app know that it is available.
  2755. obj.moveToThread(self.main_thread)
  2756. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2757. return obj
  2758. def new_excellon_object(self):
  2759. self.report_usage("new_excellon_object()")
  2760. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2761. def new_geometry_object(self):
  2762. self.report_usage("new_geometry_object()")
  2763. def initialize(obj, self):
  2764. obj.multitool = False
  2765. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2766. def new_gerber_object(self):
  2767. self.report_usage("new_gerber_object()")
  2768. def initialize(grb_obj, self):
  2769. grb_obj.multitool = False
  2770. grb_obj.source_file = []
  2771. grb_obj.multigeo = False
  2772. grb_obj.follow = False
  2773. grb_obj.apertures = {}
  2774. grb_obj.solid_geometry = []
  2775. try:
  2776. grb_obj.options['xmin'] = 0
  2777. grb_obj.options['ymin'] = 0
  2778. grb_obj.options['xmax'] = 0
  2779. grb_obj.options['ymax'] = 0
  2780. except KeyError:
  2781. pass
  2782. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2783. def on_object_created(self, obj, plot, autoselect):
  2784. """
  2785. Event callback for object creation.
  2786. :param obj: The newly created FlatCAM object.
  2787. :return: None
  2788. """
  2789. t0 = time.time() # DEBUG
  2790. self.log.debug("on_object_created()")
  2791. # The Collection might change the name if there is a collision
  2792. self.collection.append(obj)
  2793. # after adding the object to the collection always update the list of objects that are in the collection
  2794. self.all_objects_list = self.collection.get_list()
  2795. # self.inform.emit('[selected] %s created & selected: %s' %
  2796. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2797. if obj.kind == 'gerber':
  2798. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2799. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2800. elif obj.kind == 'excellon':
  2801. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2802. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2803. elif obj.kind == 'cncjob':
  2804. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2805. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2806. elif obj.kind == 'geometry':
  2807. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2808. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2809. # update the SHELL auto-completer model with the name of the new object
  2810. self.myKeywords.append(obj.options['name'])
  2811. self.shell._edit.set_model_data(self.myKeywords)
  2812. self.ui.code_editor.set_model_data(self.myKeywords)
  2813. if autoselect:
  2814. # select the just opened object but deselect the previous ones
  2815. self.collection.set_all_inactive()
  2816. self.collection.set_active(obj.options["name"])
  2817. else:
  2818. self.collection.set_all_inactive()
  2819. # here it is done the object plotting
  2820. def worker_task(t_obj):
  2821. with self.proc_container.new("Plotting"):
  2822. if isinstance(t_obj, FlatCAMCNCjob):
  2823. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2824. else:
  2825. t_obj.plot()
  2826. t1 = time.time() # DEBUG
  2827. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2828. self.object_plotted.emit(t_obj)
  2829. # Send to worker
  2830. # self.worker.add_task(worker_task, [self])
  2831. if plot is True:
  2832. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2833. def on_object_changed(self, obj):
  2834. # update the bounding box data from obj.options
  2835. xmin, ymin, xmax, ymax = obj.bounds()
  2836. obj.options['xmin'] = xmin
  2837. obj.options['ymin'] = ymin
  2838. obj.options['xmax'] = xmax
  2839. obj.options['ymax'] = ymax
  2840. log.debug("Object changed, updating the bounding box data on self.options")
  2841. # delete the old selection shape
  2842. self.delete_selection_shape()
  2843. self.should_we_save = True
  2844. def on_object_plotted(self, obj):
  2845. self.on_zoom_fit(None)
  2846. def options_read_form(self):
  2847. for option in self.options_form_fields:
  2848. self.options[option] = self.options_form_fields[option].get_value()
  2849. def options_write_form(self):
  2850. for option in self.options:
  2851. self.options_write_form_field(option)
  2852. def options_write_form_field(self, field):
  2853. try:
  2854. self.options_form_fields[field].set_value(self.options[field])
  2855. except KeyError:
  2856. # Changed from error to debug. This allows to have data stored
  2857. # which is not user-editable.
  2858. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2859. pass
  2860. def on_about(self):
  2861. """
  2862. Displays the "about" dialog.
  2863. :return: None
  2864. """
  2865. self.report_usage("on_about")
  2866. version = self.version
  2867. version_date = self.version_date
  2868. beta = self.beta
  2869. class AboutDialog(QtWidgets.QDialog):
  2870. def __init__(self, parent=None):
  2871. QtWidgets.QDialog.__init__(self, parent)
  2872. # Icon and title
  2873. self.setWindowIcon(parent.app_icon)
  2874. self.setWindowTitle("FlatCAM")
  2875. layout1 = QtWidgets.QVBoxLayout()
  2876. self.setLayout(layout1)
  2877. layout2 = QtWidgets.QHBoxLayout()
  2878. layout1.addLayout(layout2)
  2879. logo = QtWidgets.QLabel()
  2880. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2881. layout2.addWidget(logo, stretch=0)
  2882. title = QtWidgets.QLabel(
  2883. _(
  2884. "<font size=8><B>FlatCAM</B></font><BR>"
  2885. "Version {version} {beta} ({date}) - {arch} <BR>"
  2886. "<BR>"
  2887. "2D Computer-Aided Printed Circuit Board<BR>"
  2888. "Manufacturing.<BR>"
  2889. "<BR>"
  2890. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2891. "<BR>"
  2892. "<B> Main Contributors:</B><BR>"
  2893. "Denis Hayrullin<BR>"
  2894. "Kamil Sopko<BR>"
  2895. "Marius Stanciu<BR>"
  2896. "Matthieu Berthomé<BR>"
  2897. "and many others found "
  2898. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2899. "<BR>"
  2900. "Development is done "
  2901. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2902. "DOWNLOAD area "
  2903. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2904. ""
  2905. ).format(version=version,
  2906. beta=('BETA' if beta else ''),
  2907. date=version_date,
  2908. arch=platform.architecture()[0])
  2909. )
  2910. title.setOpenExternalLinks(True)
  2911. layout2.addWidget(title, stretch=1)
  2912. layout3 = QtWidgets.QHBoxLayout()
  2913. layout1.addLayout(layout3)
  2914. layout3.addStretch()
  2915. okbtn = QtWidgets.QPushButton(_("Close"))
  2916. layout3.addWidget(okbtn)
  2917. okbtn.clicked.connect(self.accept)
  2918. AboutDialog(self.ui).exec_()
  2919. def on_file_savedefaults(self):
  2920. """
  2921. Callback for menu item File->Save Defaults. Saves application default options
  2922. ``self.defaults`` to current_defaults.FlatConfig.
  2923. :return: None
  2924. """
  2925. self.save_defaults()
  2926. # def on_app_exit(self):
  2927. # self.report_usage("on_app_exit()")
  2928. #
  2929. # if self.collection.get_list():
  2930. # msgbox = QtWidgets.QMessageBox()
  2931. # # msgbox.setText("<B>Save changes ...</B>")
  2932. # msgbox.setText("There are files/objects opened in FlatCAM. "
  2933. # "\n"
  2934. # "Do you want to Save the project?")
  2935. # msgbox.setWindowTitle("Save changes")
  2936. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2937. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2938. # QtWidgets.QMessageBox.Cancel)
  2939. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2940. #
  2941. # response = msgbox.exec_()
  2942. #
  2943. # if response == QtWidgets.QMessageBox.Yes:
  2944. # self.on_file_saveprojectas(thread=False)
  2945. # elif response == QtWidgets.QMessageBox.Cancel:
  2946. # return
  2947. # self.save_defaults()
  2948. # else:
  2949. # self.save_defaults()
  2950. # log.debug("Application defaults saved ... Exit event.")
  2951. # QtWidgets.qApp.quit()
  2952. def save_defaults(self, silent=False, data_path=None):
  2953. """
  2954. Saves application default options
  2955. ``self.defaults`` to current_defaults.FlatConfig.
  2956. :return: None
  2957. """
  2958. self.report_usage("save_defaults")
  2959. if data_path is None:
  2960. data_path = self.data_path
  2961. # Read options from file
  2962. try:
  2963. f = open(data_path + "/current_defaults.FlatConfig")
  2964. defaults_file_content = f.read()
  2965. f.close()
  2966. except:
  2967. e = sys.exc_info()[0]
  2968. App.log.error("Could not load defaults file.")
  2969. App.log.error(str(e))
  2970. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2971. return
  2972. try:
  2973. defaults = json.loads(defaults_file_content)
  2974. except:
  2975. e = sys.exc_info()[0]
  2976. App.log.error("Failed to parse defaults file.")
  2977. App.log.error(str(e))
  2978. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2979. return
  2980. # Update options
  2981. self.defaults_read_form()
  2982. defaults.update(self.defaults)
  2983. self.propagate_defaults(silent=True)
  2984. # Save the toolbar view
  2985. tb_status = 0
  2986. if self.ui.toolbarfile.isVisible():
  2987. tb_status += 1
  2988. if self.ui.toolbargeo.isVisible():
  2989. tb_status += 2
  2990. if self.ui.toolbarview.isVisible():
  2991. tb_status += 4
  2992. if self.ui.toolbartools.isVisible():
  2993. tb_status += 8
  2994. if self.ui.exc_edit_toolbar.isVisible():
  2995. tb_status += 16
  2996. if self.ui.geo_edit_toolbar.isVisible():
  2997. tb_status += 32
  2998. if self.ui.grb_edit_toolbar.isVisible():
  2999. tb_status += 64
  3000. if self.ui.snap_toolbar.isVisible():
  3001. tb_status += 128
  3002. if self.ui.toolbarshell.isVisible():
  3003. tb_status += 256
  3004. self.defaults["global_toolbar_view"] = tb_status
  3005. # Save update options
  3006. try:
  3007. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3008. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3009. f.close()
  3010. except:
  3011. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  3012. return
  3013. if not silent:
  3014. self.inform.emit(_("[success] Defaults saved."))
  3015. def save_factory_defaults(self, silent=False, data_path=None):
  3016. """
  3017. Saves application factory default options
  3018. ``self.defaults`` to factory_defaults.FlatConfig.
  3019. It's a one time job done just after the first install.
  3020. :return: None
  3021. """
  3022. self.report_usage("save_factory_defaults")
  3023. if data_path is None:
  3024. data_path = self.data_path
  3025. # Read options from file
  3026. try:
  3027. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3028. factory_defaults_file_content = f_f_def.read()
  3029. f_f_def.close()
  3030. except:
  3031. e = sys.exc_info()[0]
  3032. App.log.error("Could not load factory defaults file.")
  3033. App.log.error(str(e))
  3034. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  3035. return
  3036. try:
  3037. factory_defaults = json.loads(factory_defaults_file_content)
  3038. except:
  3039. e = sys.exc_info()[0]
  3040. App.log.error("Failed to parse factory defaults file.")
  3041. App.log.error(str(e))
  3042. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  3043. return
  3044. # Update options
  3045. self.defaults_read_form()
  3046. factory_defaults.update(self.defaults)
  3047. self.propagate_defaults(silent=True)
  3048. # Save update options
  3049. try:
  3050. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3051. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3052. f_f_def_s.close()
  3053. except:
  3054. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  3055. return
  3056. if silent is False:
  3057. self.inform.emit(_("Factory defaults saved."))
  3058. def final_save(self):
  3059. if self.save_in_progress:
  3060. self.inform.emit(_("[WARNING_NOTCL] Application is saving the project. Please wait ..."))
  3061. return
  3062. if self.should_we_save and self.collection.get_list():
  3063. msgbox = QtWidgets.QMessageBox()
  3064. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3065. "\n"
  3066. "Do you want to Save the project?"))
  3067. msgbox.setWindowTitle(_("Save changes"))
  3068. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3069. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3070. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3071. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3072. msgbox.setDefaultButton(bt_yes)
  3073. msgbox.exec_()
  3074. response = msgbox.clickedButton()
  3075. if response == bt_yes:
  3076. self.on_file_saveprojectas(thread=True, quit=True)
  3077. elif response == bt_no:
  3078. self.quit_application()
  3079. elif response == bt_cancel:
  3080. return
  3081. else:
  3082. self.quit_application()
  3083. def quit_application(self):
  3084. self.save_defaults()
  3085. log.debug("App.final_save() --> App Defaults saved.")
  3086. # save toolbar state to file
  3087. settings = QSettings("Open Source", "FlatCAM")
  3088. settings.setValue('saved_gui_state', self.ui.saveState())
  3089. settings.setValue('maximized_gui', self.ui.isMaximized())
  3090. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3091. settings.setValue('notebook_font_size',
  3092. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3093. settings.setValue('axis_font_size',
  3094. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3095. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3096. # This will write the setting to the platform specific storage.
  3097. del settings
  3098. log.debug("App.final_save() --> App UI state saved.")
  3099. QtWidgets.qApp.quit()
  3100. def on_portable_checked(self, state):
  3101. line_no = 0
  3102. data = None
  3103. if sys.platform != 'win32':
  3104. # this won't work in Linux or MacOS
  3105. return
  3106. # test if the app was frozen and choose the path for the configuration file
  3107. if getattr(sys, "frozen", False) is True:
  3108. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3109. else:
  3110. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3111. config_file = current_data_path + '\\configuration.txt'
  3112. try:
  3113. with open(config_file, 'r') as f:
  3114. try:
  3115. data = f.readlines()
  3116. except Exception as e:
  3117. log.debug('App.__init__() -->%s' % str(e))
  3118. return
  3119. except FileNotFoundError:
  3120. pass
  3121. for line in data:
  3122. line = line.strip('\n')
  3123. param = str(line).rpartition('=')
  3124. if param[0] == 'portable':
  3125. break
  3126. line_no += 1
  3127. if state:
  3128. data[line_no] = 'portable=True\n'
  3129. # create the new defauults files
  3130. # create current_defaults.FlatConfig file if there is none
  3131. try:
  3132. f = open(current_data_path + '/current_defaults.FlatConfig')
  3133. f.close()
  3134. except IOError:
  3135. App.log.debug('Creating empty current_defaults.FlatConfig')
  3136. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3137. json.dump({}, f)
  3138. f.close()
  3139. # create factory_defaults.FlatConfig file if there is none
  3140. try:
  3141. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3142. f.close()
  3143. except IOError:
  3144. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3145. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3146. json.dump({}, f)
  3147. f.close()
  3148. try:
  3149. f = open(current_data_path + '/recent.json')
  3150. f.close()
  3151. except IOError:
  3152. App.log.debug('Creating empty recent.json')
  3153. f = open(current_data_path + '/recent.json', 'w')
  3154. json.dump([], f)
  3155. f.close()
  3156. try:
  3157. fp = open(current_data_path + '/recent_projects.json')
  3158. fp.close()
  3159. except IOError:
  3160. App.log.debug('Creating empty recent_projects.json')
  3161. fp = open(current_data_path + '/recent_projects.json', 'w')
  3162. json.dump([], fp)
  3163. fp.close()
  3164. # save the current defaults to the new defaults file
  3165. self.save_defaults(silent=True, data_path=current_data_path)
  3166. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3167. else:
  3168. data[line_no] = 'portable=False\n'
  3169. with open(config_file, 'w') as f:
  3170. f.writelines(data)
  3171. def on_toggle_shell(self):
  3172. """
  3173. toggle shell if is visible close it if closed open it
  3174. :return:
  3175. """
  3176. self.report_usage("on_toggle_shell()")
  3177. if self.ui.shell_dock.isVisible():
  3178. self.ui.shell_dock.hide()
  3179. else:
  3180. self.ui.shell_dock.show()
  3181. def on_edit_join(self, name=None):
  3182. """
  3183. Callback for Edit->Join. Joins the selected geometry objects into
  3184. a new one.
  3185. :return: None
  3186. """
  3187. self.report_usage("on_edit_join()")
  3188. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3189. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3190. tooldias = []
  3191. geo_type_list = set()
  3192. objs = self.collection.get_selected()
  3193. for obj in objs:
  3194. geo_type_list.add(obj.multigeo)
  3195. # if len(geo_type_list) == 1 means that all list elements are the same
  3196. if len(geo_type_list) != 1:
  3197. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  3198. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3199. "convert from one to another and retry joining \n"
  3200. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3201. "the result may not be what was expected. \n"
  3202. "Check the generated GCODE."))
  3203. return
  3204. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3205. if True in geo_type_list:
  3206. def initialize(obj, app):
  3207. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  3208. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3209. for v in obj.tools.values():
  3210. v['data']['name'] = obj_name_multi
  3211. self.new_object("geometry", obj_name_multi, initialize)
  3212. else:
  3213. def initialize(obj, app):
  3214. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  3215. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3216. for v in obj.tools.values():
  3217. v['data']['name'] = obj_name_single
  3218. self.new_object("geometry", obj_name_single, initialize)
  3219. self.should_we_save = True
  3220. def on_edit_join_exc(self):
  3221. """
  3222. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  3223. a new one.
  3224. :return: None
  3225. """
  3226. self.report_usage("on_edit_join_exc()")
  3227. objs = self.collection.get_selected()
  3228. for obj in objs:
  3229. if not isinstance(obj, FlatCAMExcellon):
  3230. self.inform.emit(_("[ERROR_NOTCL] Failed. Excellon joining works only on Excellon objects."))
  3231. return
  3232. def initialize(obj, app):
  3233. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  3234. self.new_object("excellon", 'Combo_Excellon', initialize)
  3235. self.should_we_save = True
  3236. def on_edit_join_grb(self):
  3237. """
  3238. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3239. a new one.
  3240. :return: None
  3241. """
  3242. self.report_usage("on_edit_join_grb()")
  3243. objs = self.collection.get_selected()
  3244. for obj in objs:
  3245. if not isinstance(obj, FlatCAMGerber):
  3246. self.inform.emit(_("[ERROR_NOTCL] Failed. Gerber joining works only on Gerber objects."))
  3247. return
  3248. def initialize(obj, app):
  3249. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  3250. self.new_object("gerber", 'Combo_Gerber', initialize)
  3251. self.should_we_save = True
  3252. def on_convert_singlegeo_to_multigeo(self):
  3253. self.report_usage("on_convert_singlegeo_to_multigeo()")
  3254. obj = self.collection.get_active()
  3255. if obj is None:
  3256. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  3257. return
  3258. if not isinstance(obj, FlatCAMGeometry):
  3259. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  3260. return
  3261. obj.multigeo = True
  3262. for tooluid, dict_value in obj.tools.items():
  3263. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3264. if not isinstance(obj.solid_geometry, list):
  3265. obj.solid_geometry = [obj.solid_geometry]
  3266. obj.solid_geometry[:] = []
  3267. obj.plot()
  3268. self.should_we_save = True
  3269. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  3270. def on_convert_multigeo_to_singlegeo(self):
  3271. self.report_usage("on_convert_multigeo_to_singlegeo()")
  3272. obj = self.collection.get_active()
  3273. if obj is None:
  3274. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  3275. return
  3276. if not isinstance(obj, FlatCAMGeometry):
  3277. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  3278. return
  3279. obj.multigeo = False
  3280. total_solid_geometry = []
  3281. for tooluid, dict_value in obj.tools.items():
  3282. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3283. # clear the original geometry
  3284. dict_value['solid_geometry'][:] = []
  3285. obj.solid_geometry = deepcopy(total_solid_geometry)
  3286. obj.plot()
  3287. self.should_we_save = True
  3288. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  3289. def on_options_dict_change(self, field):
  3290. self.options_write_form_field(field)
  3291. if field == "units":
  3292. self.set_screen_units(self.options['units'])
  3293. def on_defaults_dict_change(self, field):
  3294. self.defaults_write_form_field(field)
  3295. if field == "units":
  3296. self.set_screen_units(self.defaults['units'])
  3297. def set_screen_units(self, units):
  3298. self.ui.units_label.setText("[" + units.lower() + "]")
  3299. def on_toggle_units(self, no_pref=False):
  3300. """
  3301. Callback for the Units radio-button change in the Options tab.
  3302. Changes the application's default units or the current project's units.
  3303. If changing the project's units, the change propagates to all of
  3304. the objects in the project.
  3305. :return: None
  3306. """
  3307. self.report_usage("on_toggle_units")
  3308. if self.toggle_units_ignore:
  3309. return
  3310. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3311. # If option is the same, then ignore
  3312. if new_units == self.defaults["units"].upper():
  3313. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3314. return
  3315. # Options to scale
  3316. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3317. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  3318. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3319. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  3320. "excellon_z_pdepth",
  3321. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3322. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3323. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  3324. "geometry_feedrate_probe",
  3325. 'cncjob_tooldia',
  3326. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3327. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  3328. "tools_2sided_drilldia", "tools_film_boundary",
  3329. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3330. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3331. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3332. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3333. "tools_transform_offset_y",
  3334. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3335. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3336. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3337. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3338. 'global_gridx', 'global_gridy', 'global_snap_max']
  3339. def scale_options(sfactor):
  3340. for dim in dimensions:
  3341. if dim == 'excellon_toolchangexy':
  3342. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3343. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3344. coords_xy[0] *= sfactor
  3345. coords_xy[1] *= sfactor
  3346. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3347. elif dim == 'geometry_toolchangexy':
  3348. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3349. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3350. coords_xy[0] *= sfactor
  3351. coords_xy[1] *= sfactor
  3352. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3353. elif dim == 'geometry_cnctooldia':
  3354. tools_diameters = []
  3355. try:
  3356. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3357. tools_diameters = [eval(a) for a in tools_string if a != '']
  3358. except Exception as e:
  3359. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3360. self.options['geometry_cnctooldia'] = ''
  3361. for t in range(len(tools_diameters)):
  3362. tools_diameters[t] *= sfactor
  3363. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  3364. elif dim == 'tools_ncctools':
  3365. ncctools = []
  3366. try:
  3367. tools_string = self.defaults["tools_ncctools"].split(",")
  3368. ncctools = [eval(a) for a in tools_string if a != '']
  3369. except Exception as e:
  3370. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3371. self.options['tools_ncctools'] = ''
  3372. for t in range(len(ncctools)):
  3373. ncctools[t] *= sfactor
  3374. self.options['tools_ncctools'] += "%f," % ncctools[t]
  3375. elif dim == 'tools_solderpaste_tools':
  3376. sptools = []
  3377. try:
  3378. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3379. sptools = [eval(a) for a in tools_string if a != '']
  3380. except Exception as e:
  3381. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3382. self.options['tools_solderpaste_tools'] = ""
  3383. for t in range(len(sptools)):
  3384. sptools[t] *= sfactor
  3385. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  3386. elif dim == 'tools_solderpaste_xy_toolchange':
  3387. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3388. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3389. sp_coords[0] *= sfactor
  3390. sp_coords[1] *= sfactor
  3391. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  3392. elif dim == 'global_gridx' or dim == 'global_gridy':
  3393. if new_units == 'IN':
  3394. val = 0.1
  3395. try:
  3396. val = float(self.defaults[dim]) * sfactor
  3397. except Exception as e:
  3398. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3399. self.options[dim] = float('%.6f' % val)
  3400. else:
  3401. val = 0.1
  3402. try:
  3403. val = float(self.defaults[dim]) * sfactor
  3404. except Exception as e:
  3405. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3406. self.options[dim] = float('%.4f' % val)
  3407. else:
  3408. val = 0.1
  3409. try:
  3410. val = float(self.options[dim]) * sfactor
  3411. except Exception as e:
  3412. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  3413. self.options[dim] = val
  3414. def scale_defaults(sfactor):
  3415. for dim in dimensions:
  3416. if dim == 'excellon_toolchangexy':
  3417. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3418. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3419. coords_xy[0] *= sfactor
  3420. coords_xy[1] *= sfactor
  3421. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3422. elif dim == 'geometry_toolchangexy':
  3423. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3424. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3425. coords_xy[0] *= sfactor
  3426. coords_xy[1] *= sfactor
  3427. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3428. elif dim == 'geometry_cnctooldia':
  3429. tools_diameters = []
  3430. try:
  3431. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3432. tools_diameters = [eval(a) for a in tools_string if a != '']
  3433. except Exception as e:
  3434. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3435. self.defaults['geometry_cnctooldia'] = ''
  3436. for t in range(len(tools_diameters)):
  3437. tools_diameters[t] *= sfactor
  3438. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  3439. elif dim == 'tools_ncctools':
  3440. ncctools = []
  3441. try:
  3442. tools_string = self.defaults["tools_ncctools"].split(",")
  3443. ncctools = [eval(a) for a in tools_string if a != '']
  3444. except Exception as e:
  3445. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3446. self.defaults['tools_ncctools'] = ''
  3447. for t in range(len(ncctools)):
  3448. ncctools[t] *= sfactor
  3449. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  3450. elif dim == 'tools_solderpaste_tools':
  3451. sptools = []
  3452. try:
  3453. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3454. sptools = [eval(a) for a in tools_string if a != '']
  3455. except Exception as e:
  3456. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3457. self.defaults['tools_solderpaste_tools'] = ""
  3458. for t in range(len(sptools)):
  3459. sptools[t] *= sfactor
  3460. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  3461. elif dim == 'tools_solderpaste_xy_toolchange':
  3462. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3463. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3464. sp_coords[0] *= sfactor
  3465. sp_coords[1] *= sfactor
  3466. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  3467. elif dim == 'global_gridx' or dim == 'global_gridy':
  3468. if new_units == 'IN':
  3469. val = 0.1
  3470. try:
  3471. val = float(self.defaults[dim]) * sfactor
  3472. except Exception as e:
  3473. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3474. self.defaults[dim] = float('%.6f' % val)
  3475. else:
  3476. val = 0.1
  3477. try:
  3478. val = float(self.defaults[dim]) * sfactor
  3479. except Exception as e:
  3480. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3481. self.defaults[dim] = float('%.4f' % val)
  3482. else:
  3483. val = 0.1
  3484. try:
  3485. val = float(self.defaults[dim]) * sfactor
  3486. except Exception as e:
  3487. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3488. self.defaults[dim] = val
  3489. # The scaling factor depending on choice of units.
  3490. factor = 1/25.4
  3491. if new_units == 'MM':
  3492. factor = 25.4
  3493. # Changing project units. Warn user.
  3494. msgbox = QtWidgets.QMessageBox()
  3495. msgbox.setWindowTitle(_("Toggle Units"))
  3496. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  3497. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3498. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  3499. "properties of all objects to be scaled accordingly.\nContinue?"))
  3500. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3501. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3502. msgbox.setDefaultButton(bt_ok)
  3503. msgbox.exec_()
  3504. response = msgbox.clickedButton()
  3505. if response == bt_ok:
  3506. if no_pref is False:
  3507. self.options_read_form()
  3508. scale_options(factor)
  3509. self.options_write_form()
  3510. self.defaults_read_form()
  3511. scale_defaults(factor)
  3512. self.defaults_write_form(fl_units=new_units)
  3513. # save the defaults to file, some may assume that the conversion is enough and it's not
  3514. self.on_save_button()
  3515. self.should_we_save = True
  3516. # change this only if the workspace is active
  3517. if self.defaults['global_workspace'] is True:
  3518. self.plotcanvas.draw_workspace()
  3519. # adjust the grid values on the main toolbar
  3520. dec = 6 if new_units == 'IN'else 4
  3521. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  3522. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  3523. if not self.ui.grid_gap_link_cb.isChecked():
  3524. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  3525. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  3526. for obj in self.collection.get_list():
  3527. obj.convert_units(new_units)
  3528. # make that the properties stored in the object are also updated
  3529. self.object_changed.emit(obj)
  3530. obj.build_ui()
  3531. current = self.collection.get_active()
  3532. if current is not None:
  3533. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3534. if not isinstance(current, FlatCAMGeometry):
  3535. current.to_form()
  3536. self.plot_all()
  3537. self.inform.emit(_("[success] Converted units to %s") % new_units)
  3538. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  3539. self.set_screen_units(new_units)
  3540. else:
  3541. # Undo toggling
  3542. self.toggle_units_ignore = True
  3543. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3544. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3545. else:
  3546. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3547. self.toggle_units_ignore = False
  3548. self.inform.emit(_("[WARNING_NOTCL] Units conversion cancelled."))
  3549. self.options_read_form()
  3550. self.defaults_read_form()
  3551. def on_toggle_units_click(self):
  3552. try:
  3553. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3554. except (TypeError, AttributeError):
  3555. pass
  3556. if self.defaults["units"] == 'MM':
  3557. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3558. else:
  3559. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3560. self.on_toggle_units(no_pref=True)
  3561. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3562. lambda: self.on_toggle_units(no_pref=False))
  3563. def on_fullscreen(self):
  3564. self.report_usage("on_fullscreen()")
  3565. if self.toggle_fscreen is False:
  3566. if sys.platform == 'win32':
  3567. self.ui.showFullScreen()
  3568. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3569. tb.setVisible(False)
  3570. self.ui.splitter_left.setVisible(False)
  3571. self.toggle_fscreen = True
  3572. else:
  3573. if sys.platform == 'win32':
  3574. self.ui.showNormal()
  3575. self.restore_toolbar_view()
  3576. self.ui.splitter_left.setVisible(True)
  3577. self.toggle_fscreen = False
  3578. def on_toggle_plotarea(self):
  3579. self.report_usage("on_toggle_plotarea()")
  3580. try:
  3581. name = self.ui.plot_tab_area.widget(0).objectName()
  3582. except AttributeError:
  3583. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3584. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3585. self.ui.plot_tab_area.protectTab(0)
  3586. return
  3587. if name != 'plotarea':
  3588. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3589. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3590. self.ui.plot_tab_area.protectTab(0)
  3591. else:
  3592. self.ui.plot_tab_area.closeTab(0)
  3593. def on_toggle_notebook(self):
  3594. if self.ui.splitter.sizes()[0] == 0:
  3595. self.ui.splitter.setSizes([1, 1])
  3596. else:
  3597. self.ui.splitter.setSizes([0, 1])
  3598. def on_toggle_axis(self):
  3599. self.report_usage("on_toggle_axis()")
  3600. if self.toggle_axis is False:
  3601. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3602. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3603. self.plotcanvas.redraw()
  3604. self.toggle_axis = True
  3605. else:
  3606. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3607. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3608. self.plotcanvas.redraw()
  3609. self.toggle_axis = False
  3610. def on_toggle_grid(self):
  3611. self.report_usage("on_toggle_grid()")
  3612. self.ui.grid_snap_btn.trigger()
  3613. def on_options_combo_change(self, sel):
  3614. """
  3615. Called when the combo box to choose between application defaults and
  3616. project option changes value. The corresponding variables are
  3617. copied to the UI.
  3618. :param sel: The option index that was chosen.
  3619. :return: None
  3620. """
  3621. # combo_sel = self.ui.notebook.combo_options.get_active()
  3622. App.log.debug("Options --> %s" % sel)
  3623. # form = [self.defaults_form, self.options_form][sel]
  3624. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  3625. if sel == 0:
  3626. self.gen_form = self.ui.general_defaults_form
  3627. self.ger_form = self.ui.gerber_defaults_form
  3628. self.exc_form = self.ui.excellon_defaults_form
  3629. self.geo_form = self.ui.geometry_defaults_form
  3630. self.cnc_form = self.ui.cncjob_defaults_form
  3631. self.tools_form = self.ui.tools_defaults_form
  3632. elif sel == 1:
  3633. self.gen_form = self.ui.general_options_form
  3634. self.ger_form = self.ui.gerber_options_form
  3635. self.exc_form = self.ui.excellon_options_form
  3636. self.geo_form = self.ui.geometry_options_form
  3637. self.cnc_form = self.ui.cncjob_options_form
  3638. self.tools_form = self.ui.tools_options_form
  3639. else:
  3640. return
  3641. try:
  3642. self.ui.general_scroll_area.takeWidget()
  3643. except:
  3644. self.log.debug("Nothing to remove")
  3645. self.ui.general_scroll_area.setWidget(self.gen_form)
  3646. self.gen_form.show()
  3647. try:
  3648. self.ui.gerber_scroll_area.takeWidget()
  3649. except:
  3650. self.log.debug("Nothing to remove")
  3651. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  3652. self.ger_form.show()
  3653. try:
  3654. self.ui.excellon_scroll_area.takeWidget()
  3655. except:
  3656. self.log.debug("Nothing to remove")
  3657. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  3658. self.exc_form.show()
  3659. try:
  3660. self.ui.geometry_scroll_area.takeWidget()
  3661. except:
  3662. self.log.debug("Nothing to remove")
  3663. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  3664. self.geo_form.show()
  3665. try:
  3666. self.ui.cncjob_scroll_area.takeWidget()
  3667. except:
  3668. self.log.debug("Nothing to remove")
  3669. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  3670. self.cnc_form.show()
  3671. try:
  3672. self.ui.tools_scroll_area.takeWidget()
  3673. except:
  3674. self.log.debug("Nothing to remove")
  3675. self.ui.tools_scroll_area.setWidget(self.tools_form)
  3676. self.tools_form.show()
  3677. self.log.debug("Finished GUI form initialization.")
  3678. # self.options2form()
  3679. def on_excellon_defaults_button(self):
  3680. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  3681. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  3682. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  3683. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  3684. self.defaults_form_fields["excellon_zeros"].set_value('L')
  3685. self.defaults_form_fields["excellon_units"].set_value('INCH')
  3686. log.debug("Excellon app defaults loaded ...")
  3687. def on_excellon_options_button(self):
  3688. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  3689. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  3690. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  3691. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  3692. self.options_form_fields["excellon_zeros"].set_value('L')
  3693. self.options_form_fields["excellon_units"].set_value('INCH')
  3694. log.debug("Excellon options defaults loaded ...")
  3695. # Setting plot colors handlers
  3696. def on_pf_color_entry(self):
  3697. self.defaults['global_plot_fill'] = \
  3698. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  3699. self.defaults['global_plot_fill'][7:9]
  3700. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3701. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  3702. def on_pf_color_button(self):
  3703. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  3704. c_dialog = QtWidgets.QColorDialog()
  3705. plot_fill_color = c_dialog.getColor(initial=current_color)
  3706. if plot_fill_color.isValid() is False:
  3707. return
  3708. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3709. "background-color:%s" % str(plot_fill_color.name()))
  3710. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  3711. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  3712. self.defaults['global_plot_fill'] = new_val
  3713. def on_pf_color_spinner(self):
  3714. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  3715. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  3716. self.defaults['global_plot_fill'] = \
  3717. self.defaults['global_plot_fill'][:7] + \
  3718. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3719. self.defaults['global_plot_line'] = \
  3720. self.defaults['global_plot_line'][:7] + \
  3721. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3722. def on_pf_color_slider(self):
  3723. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  3724. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  3725. def on_pl_color_entry(self):
  3726. self.defaults['global_plot_line'] = \
  3727. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  3728. self.defaults['global_plot_line'][7:9]
  3729. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3730. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  3731. def on_pl_color_button(self):
  3732. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  3733. # print(current_color)
  3734. c_dialog = QtWidgets.QColorDialog()
  3735. plot_line_color = c_dialog.getColor(initial=current_color)
  3736. if plot_line_color.isValid() is False:
  3737. return
  3738. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3739. "background-color:%s" % str(plot_line_color.name()))
  3740. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  3741. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  3742. self.defaults['global_plot_line'] = new_val_line
  3743. # Setting selection colors (left - right) handlers
  3744. def on_sf_color_entry(self):
  3745. self.defaults['global_sel_fill'] = \
  3746. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  3747. self.defaults['global_sel_fill'][7:9]
  3748. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3749. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  3750. def on_sf_color_button(self):
  3751. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  3752. c_dialog = QtWidgets.QColorDialog()
  3753. plot_fill_color = c_dialog.getColor(initial=current_color)
  3754. if plot_fill_color.isValid() is False:
  3755. return
  3756. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3757. "background-color:%s" % str(plot_fill_color.name()))
  3758. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  3759. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  3760. self.defaults['global_sel_fill'] = new_val
  3761. def on_sf_color_spinner(self):
  3762. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  3763. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  3764. self.defaults['global_sel_fill'] = \
  3765. self.defaults['global_sel_fill'][:7] + \
  3766. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3767. self.defaults['global_sel_line'] = \
  3768. self.defaults['global_sel_line'][:7] + \
  3769. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3770. def on_sf_color_slider(self):
  3771. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  3772. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  3773. def on_sl_color_entry(self):
  3774. self.defaults['global_sel_line'] = \
  3775. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  3776. self.defaults['global_sel_line'][7:9]
  3777. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3778. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  3779. def on_sl_color_button(self):
  3780. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  3781. c_dialog = QtWidgets.QColorDialog()
  3782. plot_line_color = c_dialog.getColor(initial=current_color)
  3783. if plot_line_color.isValid() is False:
  3784. return
  3785. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3786. "background-color:%s" % str(plot_line_color.name()))
  3787. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  3788. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  3789. self.defaults['global_sel_line'] = new_val_line
  3790. # Setting selection colors (right - left) handlers
  3791. def on_alt_sf_color_entry(self):
  3792. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  3793. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  3794. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3795. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  3796. def on_alt_sf_color_button(self):
  3797. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  3798. c_dialog = QtWidgets.QColorDialog()
  3799. plot_fill_color = c_dialog.getColor(initial=current_color)
  3800. if plot_fill_color.isValid() is False:
  3801. return
  3802. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3803. "background-color:%s" % str(plot_fill_color.name()))
  3804. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  3805. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  3806. self.defaults['global_alt_sel_fill'] = new_val
  3807. def on_alt_sf_color_spinner(self):
  3808. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  3809. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  3810. self.defaults['global_alt_sel_fill'] = \
  3811. self.defaults['global_alt_sel_fill'][:7] + \
  3812. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3813. self.defaults['global_alt_sel_line'] = \
  3814. self.defaults['global_alt_sel_line'][:7] + \
  3815. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3816. def on_alt_sf_color_slider(self):
  3817. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  3818. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  3819. def on_alt_sl_color_entry(self):
  3820. self.defaults['global_alt_sel_line'] = \
  3821. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  3822. self.defaults['global_alt_sel_line'][7:9]
  3823. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3824. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  3825. def on_alt_sl_color_button(self):
  3826. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  3827. c_dialog = QtWidgets.QColorDialog()
  3828. plot_line_color = c_dialog.getColor(initial=current_color)
  3829. if plot_line_color.isValid() is False:
  3830. return
  3831. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3832. "background-color:%s" % str(plot_line_color.name()))
  3833. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  3834. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  3835. self.defaults['global_alt_sel_line'] = new_val_line
  3836. # Setting Editor colors
  3837. def on_draw_color_entry(self):
  3838. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3839. .draw_color_entry.get_value()
  3840. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3841. "background-color:%s" % str(self.defaults['global_draw_color']))
  3842. def on_draw_color_button(self):
  3843. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  3844. c_dialog = QtWidgets.QColorDialog()
  3845. draw_color = c_dialog.getColor(initial=current_color)
  3846. if draw_color.isValid() is False:
  3847. return
  3848. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3849. "background-color:%s" % str(draw_color.name()))
  3850. new_val = str(draw_color.name())
  3851. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  3852. self.defaults['global_draw_color'] = new_val
  3853. def on_sel_draw_color_entry(self):
  3854. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3855. .sel_draw_color_entry.get_value()
  3856. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3857. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3858. def on_sel_draw_color_button(self):
  3859. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3860. c_dialog = QtWidgets.QColorDialog()
  3861. sel_draw_color = c_dialog.getColor(initial=current_color)
  3862. if sel_draw_color.isValid() is False:
  3863. return
  3864. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3865. "background-color:%s" % str(sel_draw_color.name()))
  3866. new_val_sel = str(sel_draw_color.name())
  3867. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3868. self.defaults['global_sel_draw_color'] = new_val_sel
  3869. def on_proj_color_entry(self):
  3870. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  3871. .proj_color_entry.get_value()
  3872. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3873. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  3874. def on_proj_color_button(self):
  3875. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  3876. c_dialog = QtWidgets.QColorDialog()
  3877. proj_color = c_dialog.getColor(initial=current_color)
  3878. if proj_color.isValid() is False:
  3879. return
  3880. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3881. "background-color:%s" % str(proj_color.name()))
  3882. new_val_sel = str(proj_color.name())
  3883. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  3884. self.defaults['global_proj_item_color'] = new_val_sel
  3885. def on_proj_color_dis_entry(self):
  3886. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  3887. .proj_color_dis_entry.get_value()
  3888. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3889. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  3890. def on_proj_color_dis_button(self):
  3891. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  3892. c_dialog = QtWidgets.QColorDialog()
  3893. proj_color = c_dialog.getColor(initial=current_color)
  3894. if proj_color.isValid() is False:
  3895. return
  3896. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3897. "background-color:%s" % str(proj_color.name()))
  3898. new_val_sel = str(proj_color.name())
  3899. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  3900. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3901. def on_annotation_fontcolor_entry(self):
  3902. self.defaults['cncjob_annotation_fontcolor'] = \
  3903. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.get_value()
  3904. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  3905. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  3906. def on_annotation_fontcolor_button(self):
  3907. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  3908. c_dialog = QtWidgets.QColorDialog()
  3909. annotation_color = c_dialog.getColor(initial=current_color)
  3910. if annotation_color.isValid() is False:
  3911. return
  3912. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  3913. "background-color:%s" % str(annotation_color.name()))
  3914. new_val_sel = str(annotation_color.name())
  3915. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(new_val_sel)
  3916. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3917. def on_notebook_tab_rmb_click(self, checked):
  3918. self.ui.notebook.set_detachable(val=checked)
  3919. self.defaults["global_tabs_detachable"] = checked
  3920. self.ui.plot_tab_area.set_detachable(val=checked)
  3921. self.defaults["global_tabs_detachable"] = checked
  3922. def on_deselect_all(self):
  3923. self.collection.set_all_inactive()
  3924. self.delete_selection_shape()
  3925. def on_workspace_modified(self):
  3926. self.save_defaults(silent=True)
  3927. self.plotcanvas.draw_workspace()
  3928. def on_workspace(self):
  3929. self.report_usage("on_workspace()")
  3930. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3931. self.plotcanvas.restore_workspace()
  3932. else:
  3933. self.plotcanvas.delete_workspace()
  3934. self.save_defaults(silent=True)
  3935. def on_workspace_menu(self):
  3936. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3937. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3938. else:
  3939. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3940. self.on_workspace()
  3941. def on_layout(self, index=None, lay=None):
  3942. self.report_usage("on_layout()")
  3943. if lay:
  3944. current_layout = lay
  3945. else:
  3946. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  3947. settings = QSettings("Open Source", "FlatCAM")
  3948. settings.setValue('layout', current_layout)
  3949. # This will write the setting to the platform specific storage.
  3950. del settings
  3951. # first remove the toolbars:
  3952. try:
  3953. self.ui.removeToolBar(self.ui.toolbarfile)
  3954. self.ui.removeToolBar(self.ui.toolbargeo)
  3955. self.ui.removeToolBar(self.ui.toolbarview)
  3956. self.ui.removeToolBar(self.ui.toolbarshell)
  3957. self.ui.removeToolBar(self.ui.toolbartools)
  3958. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3959. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3960. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  3961. self.ui.removeToolBar(self.ui.snap_toolbar)
  3962. self.ui.removeToolBar(self.ui.toolbarshell)
  3963. except Exception as e:
  3964. pass
  3965. if current_layout == 'standard':
  3966. # ## TOOLBAR INSTALLATION # ##
  3967. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3968. self.ui.toolbarfile.setObjectName('File_TB')
  3969. self.ui.addToolBar(self.ui.toolbarfile)
  3970. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3971. self.ui.toolbargeo.setObjectName('Edit_TB')
  3972. self.ui.addToolBar(self.ui.toolbargeo)
  3973. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3974. self.ui.toolbarview.setObjectName('View_TB')
  3975. self.ui.addToolBar(self.ui.toolbarview)
  3976. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3977. self.ui.toolbarshell.setObjectName('Shell_TB')
  3978. self.ui.addToolBar(self.ui.toolbarshell)
  3979. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3980. self.ui.toolbartools.setObjectName('Tools_TB')
  3981. self.ui.addToolBar(self.ui.toolbartools)
  3982. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3983. self.ui.exc_edit_toolbar.setVisible(False)
  3984. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3985. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3986. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3987. self.ui.geo_edit_toolbar.setVisible(False)
  3988. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3989. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3990. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3991. self.ui.grb_edit_toolbar.setVisible(False)
  3992. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3993. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  3994. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3995. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3996. # self.ui.snap_toolbar.setMaximumHeight(30)
  3997. self.ui.addToolBar(self.ui.snap_toolbar)
  3998. self.ui.corner_snap_btn.setVisible(False)
  3999. self.ui.snap_magnet.setVisible(False)
  4000. elif current_layout == 'compact':
  4001. # ## TOOLBAR INSTALLATION # ##
  4002. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4003. self.ui.toolbarfile.setObjectName('File_TB')
  4004. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  4005. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4006. self.ui.toolbargeo.setObjectName('Edit_TB')
  4007. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  4008. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4009. self.ui.toolbarview.setObjectName('View_TB')
  4010. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  4011. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4012. self.ui.toolbarshell.setObjectName('Shell_TB')
  4013. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  4014. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4015. self.ui.toolbartools.setObjectName('Tools_TB')
  4016. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  4017. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4018. # self.ui.geo_edit_toolbar.setVisible(False)
  4019. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4020. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  4021. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4022. # self.ui.grb_edit_toolbar.setVisible(False)
  4023. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4024. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  4025. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4026. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4027. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  4028. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4029. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4030. self.ui.snap_toolbar.setMaximumHeight(30)
  4031. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  4032. self.ui.corner_snap_btn.setVisible(True)
  4033. self.ui.snap_magnet.setVisible(True)
  4034. # add all the actions to the toolbars
  4035. self.ui.populate_toolbars()
  4036. # reconnect all the signals to the toolbar actions
  4037. self.connect_toolbar_signals()
  4038. self.ui.grid_snap_btn.setChecked(True)
  4039. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  4040. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  4041. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  4042. self.ui.grid_gap_link_cb.setChecked(True)
  4043. def on_cnc_custom_parameters(self, signal_text):
  4044. if signal_text == 'Parameters':
  4045. return
  4046. else:
  4047. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4048. def on_save_button(self):
  4049. log.debug("App.on_save_button() --> Saving preferences to file.")
  4050. self.preferences_changed_flag = False
  4051. self.save_defaults(silent=False)
  4052. # load the defaults so they are updated into the app
  4053. self.load_defaults(filename='current_defaults')
  4054. # Re-fresh project options
  4055. self.on_options_app2project()
  4056. # save the notebook font size
  4057. settings = QSettings("Open Source", "FlatCAM")
  4058. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4059. settings.setValue('notebook_font_size', fsize)
  4060. # save the axis font size
  4061. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4062. settings.setValue('axis_font_size', g_fsize)
  4063. # This will write the setting to the platform specific storage.
  4064. del settings
  4065. def handlePrint(self):
  4066. self.report_usage("handlePrint()")
  4067. dialog = QtPrintSupport.QPrintDialog()
  4068. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  4069. self.ui.code_editor.document().print_(dialog.printer())
  4070. def handlePreview(self):
  4071. self.report_usage("handlePreview()")
  4072. dialog = QtPrintSupport.QPrintPreviewDialog()
  4073. dialog.paintRequested.connect(self.ui.code_editor.print_)
  4074. dialog.exec_()
  4075. def handleTextChanged(self):
  4076. # enable = not self.ui.code_editor.document().isEmpty()
  4077. # self.ui.buttonPrint.setEnabled(enable)
  4078. # self.ui.buttonPreview.setEnabled(enable)
  4079. pass
  4080. def handleOpen(self, filt=None):
  4081. self.report_usage("handleOpen()")
  4082. if filt:
  4083. _filter_ = filt
  4084. else:
  4085. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4086. "All Files (*.*)"
  4087. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  4088. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  4089. if path:
  4090. file = QtCore.QFile(path)
  4091. if file.open(QtCore.QIODevice.ReadOnly):
  4092. stream = QtCore.QTextStream(file)
  4093. self.gcode_edited = stream.readAll()
  4094. self.ui.code_editor.setPlainText(self.gcode_edited)
  4095. file.close()
  4096. def handleSaveGCode(self, name=None, filt=None):
  4097. self.report_usage("handleSaveGCode()")
  4098. if filt:
  4099. _filter_ = filt
  4100. else:
  4101. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4102. "All Files (*.*)"
  4103. if name:
  4104. obj_name = name
  4105. else:
  4106. try:
  4107. obj_name = self.collection.get_active().options['name']
  4108. except AttributeError:
  4109. obj_name = 'file'
  4110. if filt is None:
  4111. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  4112. try:
  4113. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  4114. caption=_("Export G-Code ..."),
  4115. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  4116. filter=_filter_
  4117. )[0])
  4118. except TypeError:
  4119. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  4120. if filename == "":
  4121. self.inform.emit(_("[WARNING_NOTCL] Export Code cancelled."))
  4122. return
  4123. else:
  4124. try:
  4125. my_gcode = self.ui.code_editor.toPlainText()
  4126. with open(filename, 'w') as f:
  4127. for line in my_gcode:
  4128. f.write(line)
  4129. except FileNotFoundError:
  4130. self.inform.emit(_("[WARNING] No such file or directory"))
  4131. return
  4132. except PermissionError:
  4133. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  4134. "Most likely another app is holding the file open and not accessible."))
  4135. return
  4136. # Just for adding it to the recent files list.
  4137. if self.defaults["global_open_style"] is False:
  4138. self.file_opened.emit("cncjob", filename)
  4139. self.file_saved.emit("cncjob", filename)
  4140. self.inform.emit(_("Saved to: %s") % filename)
  4141. def handleFindGCode(self):
  4142. self.report_usage("handleFindGCode()")
  4143. flags = QtGui.QTextDocument.FindCaseSensitively
  4144. text_to_be_found = self.ui.entryFind.get_value()
  4145. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  4146. if r is False:
  4147. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4148. def handleReplaceGCode(self):
  4149. self.report_usage("handleReplaceGCode()")
  4150. old = self.ui.entryFind.get_value()
  4151. new = self.ui.entryReplace.get_value()
  4152. if self.ui.sel_all_cb.isChecked():
  4153. while True:
  4154. cursor = self.ui.code_editor.textCursor()
  4155. cursor.beginEditBlock()
  4156. flags = QtGui.QTextDocument.FindCaseSensitively
  4157. # self.ui.editor is the QPlainTextEdit
  4158. r = self.ui.code_editor.find(str(old), flags)
  4159. if r:
  4160. qc = self.ui.code_editor.textCursor()
  4161. if qc.hasSelection():
  4162. qc.insertText(new)
  4163. else:
  4164. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4165. break
  4166. # Mark end of undo block
  4167. cursor.endEditBlock()
  4168. else:
  4169. cursor = self.ui.code_editor.textCursor()
  4170. cursor.beginEditBlock()
  4171. qc = self.ui.code_editor.textCursor()
  4172. if qc.hasSelection():
  4173. qc.insertText(new)
  4174. # Mark end of undo block
  4175. cursor.endEditBlock()
  4176. def on_tool_add_keypress(self):
  4177. # ## Current application units in Upper Case
  4178. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4179. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4180. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4181. if notebook_widget_name == 'selected_tab':
  4182. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4183. # Tool add works for Geometry only if Advanced is True in Preferences
  4184. if self.defaults["global_app_level"] == 'a':
  4185. tool_add_popup = FCInputDialog(title="New Tool ...",
  4186. text='Enter a Tool Diameter:',
  4187. min=0.0000, max=99.9999, decimals=4)
  4188. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4189. val, ok = tool_add_popup.get_value()
  4190. if ok:
  4191. if float(val) == 0:
  4192. self.inform.emit(
  4193. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4194. return
  4195. self.collection.get_active().on_tool_add(dia=float(val))
  4196. else:
  4197. self.inform.emit(
  4198. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4199. else:
  4200. msgbox = QtWidgets.QMessageBox()
  4201. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4202. "Go to Preferences -> General - Show Advanced Options."))
  4203. msgbox.setWindowTitle("Tool adding ...")
  4204. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  4205. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4206. msgbox.setDefaultButton(bt_ok)
  4207. msgbox.exec_()
  4208. # work only if the notebook tab on focus is the Tools_Tab
  4209. if notebook_widget_name == 'tool_tab':
  4210. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4211. tool_add_popup = FCInputDialog(title="New Tool ...",
  4212. text='Enter a Tool Diameter:',
  4213. min=0.0000, max=99.9999, decimals=4)
  4214. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4215. val, ok = tool_add_popup.get_value()
  4216. # and only if the tool is NCC Tool
  4217. if tool_widget == self.ncclear_tool.toolName:
  4218. if ok:
  4219. if float(val) == 0:
  4220. self.inform.emit(
  4221. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4222. return
  4223. self.ncclear_tool.on_tool_add(dia=float(val))
  4224. else:
  4225. self.inform.emit(
  4226. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4227. # and only if the tool is Paint Area Tool
  4228. elif tool_widget == self.paint_tool.toolName:
  4229. if ok:
  4230. if float(val) == 0:
  4231. self.inform.emit(
  4232. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4233. return
  4234. self.paint_tool.on_tool_add(dia=float(val))
  4235. else:
  4236. self.inform.emit(
  4237. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4238. # and only if the tool is Solder Paste Dispensing Tool
  4239. elif tool_widget == self.paste_tool.toolName:
  4240. if ok:
  4241. if float(val) == 0:
  4242. self.inform.emit(
  4243. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4244. return
  4245. self.paste_tool.on_tool_add(dia=float(val))
  4246. else:
  4247. self.inform.emit(
  4248. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4249. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4250. # See description bellow.
  4251. def on_delete_keypress(self):
  4252. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4253. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4254. if notebook_widget_name == 'selected_tab':
  4255. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4256. self.collection.get_active().on_tool_delete()
  4257. # work only if the notebook tab on focus is the Tools_Tab
  4258. elif notebook_widget_name == 'tool_tab':
  4259. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4260. # and only if the tool is NCC Tool
  4261. if tool_widget == self.ncclear_tool.toolName:
  4262. self.ncclear_tool.on_tool_delete()
  4263. # and only if the tool is Paint Tool
  4264. elif tool_widget == self.paint_tool.toolName:
  4265. self.paint_tool.on_tool_delete()
  4266. # and only if the tool is Solder Paste Dispensing Tool
  4267. elif tool_widget == self.paste_tool.toolName:
  4268. self.paste_tool.on_tool_delete()
  4269. else:
  4270. self.on_delete()
  4271. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4272. # some screens you have to be careful where you hover with your mouse.
  4273. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4274. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4275. # Complicated, I know :)
  4276. def on_delete(self):
  4277. """
  4278. Delete the currently selected FlatCAMObjs.
  4279. :return: None
  4280. """
  4281. self.report_usage("on_delete()")
  4282. response = None
  4283. bt_ok = None
  4284. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4285. # a geometry object before we update it.
  4286. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4287. and self.grb_editor.editor_active is False:
  4288. if self.defaults["global_delete_confirmation"] is True:
  4289. msgbox = QtWidgets.QMessageBox()
  4290. msgbox.setWindowTitle(_("Delete objects"))
  4291. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  4292. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4293. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4294. "the selected objects?"))
  4295. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4296. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4297. msgbox.setDefaultButton(bt_ok)
  4298. msgbox.exec_()
  4299. response = msgbox.clickedButton()
  4300. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  4301. if self.collection.get_active():
  4302. self.log.debug("App.on_delete()")
  4303. while self.collection.get_active():
  4304. obj_active = self.collection.get_active()
  4305. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  4306. if isinstance(obj_active, FlatCAMGerber):
  4307. for el in obj_active.mark_shapes:
  4308. obj_active.mark_shapes[el].clear(update=True)
  4309. obj_active.mark_shapes[el].enabled = False
  4310. obj_active.mark_shapes[el] = None
  4311. elif isinstance(obj_active, FlatCAMCNCjob):
  4312. try:
  4313. obj_active.annotation.clear(update=True)
  4314. obj_active.annotation.enabled = False
  4315. except AttributeError:
  4316. pass
  4317. self.delete_first_selected()
  4318. self.inform.emit(_("Object(s) deleted ..."))
  4319. # make sure that the selection shape is deleted, too
  4320. self.delete_selection_shape()
  4321. else:
  4322. self.inform.emit(_("Failed. No object(s) selected..."))
  4323. else:
  4324. self.inform.emit(_("Save the work in Editor and try again ..."))
  4325. def delete_first_selected(self):
  4326. # Keep this for later
  4327. try:
  4328. sel_obj = self.collection.get_active()
  4329. name = sel_obj.options["name"]
  4330. except AttributeError:
  4331. self.log.debug("Nothing selected for deletion")
  4332. return
  4333. # Remove from dictionary
  4334. self.collection.delete_active()
  4335. # Clear form
  4336. self.setup_component_editor()
  4337. self.inform.emit("Object deleted: %s" % name)
  4338. def on_set_origin(self):
  4339. """
  4340. Set the origin to the left mouse click position
  4341. :return: None
  4342. """
  4343. # display the message for the user
  4344. # and ask him to click on the desired position
  4345. self.report_usage("on_set_origin()")
  4346. self.inform.emit(_('Click to set the origin ...'))
  4347. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  4348. def on_jump_to(self, custom_location=None, fit_center=True):
  4349. """
  4350. Jump to a location by setting the mouse cursor location
  4351. :return:
  4352. """
  4353. self.report_usage("on_jump_to()")
  4354. if not custom_location:
  4355. dia_box = Dialog_box(title=_("Jump to ..."),
  4356. label=_("Enter the coordinates in format X,Y:"),
  4357. icon=QtGui.QIcon('share/jump_to16.png'))
  4358. if dia_box.ok is True:
  4359. try:
  4360. location = eval(dia_box.location)
  4361. if not isinstance(location, tuple):
  4362. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4363. return
  4364. except:
  4365. return
  4366. else:
  4367. return
  4368. else:
  4369. location = custom_location
  4370. if fit_center:
  4371. self.plotcanvas.fit_center(loc=location)
  4372. cursor = QtGui.QCursor()
  4373. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4374. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  4375. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  4376. self.inform.emit(_("[success] Done."))
  4377. return location
  4378. def on_copy_object(self):
  4379. self.report_usage("on_copy_object()")
  4380. def initialize(obj_init, app):
  4381. obj_init.solid_geometry = obj.solid_geometry
  4382. try:
  4383. obj_init.follow_geometry = obj.follow_geometry
  4384. except AttributeError:
  4385. pass
  4386. try:
  4387. obj_init.apertures = obj.apertures
  4388. except AttributeError:
  4389. pass
  4390. try:
  4391. if obj.tools:
  4392. obj_init.tools = obj.tools
  4393. except Exception as e:
  4394. log.debug("App.on_copy_object() --> %s" % str(e))
  4395. def initialize_excellon(obj_init, app):
  4396. obj_init.tools = obj.tools
  4397. # drills are offset, so they need to be deep copied
  4398. obj_init.drills = deepcopy(obj.drills)
  4399. # slots are offset, so they need to be deep copied
  4400. obj_init.slots = deepcopy(obj.slots)
  4401. obj_init.create_geometry()
  4402. for obj in self.collection.get_selected():
  4403. obj_name = obj.options["name"]
  4404. try:
  4405. if isinstance(obj, FlatCAMExcellon):
  4406. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4407. elif isinstance(obj, FlatCAMGerber):
  4408. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4409. elif isinstance(obj, FlatCAMGeometry):
  4410. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4411. except Exception as e:
  4412. return "Operation failed: %s" % str(e)
  4413. def on_copy_object2(self, custom_name):
  4414. def initialize_geometry(obj_init, app):
  4415. obj_init.solid_geometry = obj.solid_geometry
  4416. try:
  4417. obj_init.follow_geometry = obj.follow_geometry
  4418. except AttributeError:
  4419. pass
  4420. try:
  4421. obj_init.apertures = obj.apertures
  4422. except AttributeError:
  4423. pass
  4424. try:
  4425. if obj.tools:
  4426. obj_init.tools = obj.tools
  4427. except Exception as e:
  4428. log.debug("on_copy_object2() --> %s" % str(e))
  4429. def initialize_gerber(obj_init, app):
  4430. obj_init.solid_geometry = obj.solid_geometry
  4431. obj_init.apertures = deepcopy(obj.apertures)
  4432. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4433. def initialize_excellon(obj_init, app):
  4434. obj_init.tools = obj.tools
  4435. # drills are offset, so they need to be deep copied
  4436. obj_init.drills = deepcopy(obj.drills)
  4437. # slots are offset, so they need to be deep copied
  4438. obj_init.slots = deepcopy(obj.slots)
  4439. obj_init.create_geometry()
  4440. for obj in self.collection.get_selected():
  4441. obj_name = obj.options["name"]
  4442. try:
  4443. if isinstance(obj, FlatCAMExcellon):
  4444. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4445. elif isinstance(obj, FlatCAMGerber):
  4446. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4447. elif isinstance(obj, FlatCAMGeometry):
  4448. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4449. except Exception as e:
  4450. return "Operation failed: %s" % str(e)
  4451. def on_rename_object(self, text):
  4452. self.report_usage("on_rename_object()")
  4453. named_obj = self.collection.get_active()
  4454. for obj in named_obj:
  4455. if obj is list:
  4456. self.on_rename_object(text)
  4457. else:
  4458. try:
  4459. obj.options['name'] = text
  4460. except Exception as e:
  4461. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4462. def convert_any2geo(self):
  4463. self.report_usage("convert_any2geo()")
  4464. def initialize(obj_init, app):
  4465. obj_init.solid_geometry = obj.solid_geometry
  4466. try:
  4467. obj_init.follow_geometry = obj.follow_geometry
  4468. except AttributeError:
  4469. pass
  4470. try:
  4471. obj_init.apertures = obj.apertures
  4472. except AttributeError:
  4473. pass
  4474. try:
  4475. if obj.tools:
  4476. obj_init.tools = obj.tools
  4477. except AttributeError:
  4478. pass
  4479. def initialize_excellon(obj_init, app):
  4480. # objs = self.collection.get_selected()
  4481. # FlatCAMGeometry.merge(objs, obj)
  4482. solid_geo = []
  4483. for tool in obj.tools:
  4484. for geo in obj.tools[tool]['solid_geometry']:
  4485. solid_geo.append(geo)
  4486. obj_init.solid_geometry = deepcopy(solid_geo)
  4487. if not self.collection.get_selected():
  4488. log.warning("App.convert_any2geo --> No object selected")
  4489. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4490. return
  4491. for obj in self.collection.get_selected():
  4492. obj_name = obj.options["name"]
  4493. try:
  4494. if isinstance(obj, FlatCAMExcellon):
  4495. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4496. else:
  4497. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4498. except Exception as e:
  4499. return "Operation failed: %s" % str(e)
  4500. def convert_any2gerber(self):
  4501. self.report_usage("convert_any2gerber()")
  4502. def initialize_geometry(obj_init, app):
  4503. apertures = {}
  4504. apid = 0
  4505. apertures[str(apid)] = {}
  4506. apertures[str(apid)]['geometry'] = []
  4507. for obj_orig in obj.solid_geometry:
  4508. new_elem = dict()
  4509. new_elem['solid'] = obj_orig
  4510. new_elem['follow'] = obj_orig.exterior
  4511. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4512. apertures[str(apid)]['size'] = 0.0
  4513. apertures[str(apid)]['type'] = 'C'
  4514. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4515. obj_init.apertures = deepcopy(apertures)
  4516. def initialize_excellon(obj_init, app):
  4517. apertures = {}
  4518. apid = 10
  4519. for tool in obj.tools:
  4520. apertures[str(apid)] = {}
  4521. apertures[str(apid)]['geometry'] = []
  4522. for geo in obj.tools[tool]['solid_geometry']:
  4523. new_el = dict()
  4524. new_el['solid'] = geo
  4525. new_el['follow'] = geo.exterior
  4526. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4527. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4528. apertures[str(apid)]['type'] = 'C'
  4529. apid += 1
  4530. # create solid_geometry
  4531. solid_geometry = []
  4532. for apid in apertures:
  4533. for geo_el in apertures[apid]['geometry']:
  4534. solid_geometry.append(geo_el['solid'])
  4535. solid_geometry = MultiPolygon(solid_geometry)
  4536. solid_geometry = solid_geometry.buffer(0.0000001)
  4537. obj_init.solid_geometry = deepcopy(solid_geometry)
  4538. obj_init.apertures = deepcopy(apertures)
  4539. # clear the working objects (perhaps not necessary due of Python GC)
  4540. apertures.clear()
  4541. if not self.collection.get_selected():
  4542. log.warning("App.convert_any2gerber --> No object selected")
  4543. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4544. return
  4545. for obj in self.collection.get_selected():
  4546. obj_name = obj.options["name"]
  4547. try:
  4548. if isinstance(obj, FlatCAMExcellon):
  4549. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4550. elif isinstance(obj, FlatCAMGeometry):
  4551. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4552. else:
  4553. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4554. except Exception as e:
  4555. return "Operation failed: %s" % str(e)
  4556. def on_set_zero_click(self, event):
  4557. # this function will be available only for mouse left click
  4558. pos = []
  4559. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  4560. if event.button == 1:
  4561. if self.grid_status() == True:
  4562. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4563. else:
  4564. pos = pos_canvas
  4565. x = 0 - pos[0]
  4566. y = 0 - pos[1]
  4567. for obj in self.collection.get_list():
  4568. obj.offset((x, y))
  4569. self.object_changed.emit(obj)
  4570. obj.plot()
  4571. # Update the object bounding box options
  4572. a, b, c, d = obj.bounds()
  4573. obj.options['xmin'] = a
  4574. obj.options['ymin'] = b
  4575. obj.options['xmax'] = c
  4576. obj.options['ymax'] = d
  4577. # self.plot_all(zoom=False)
  4578. self.inform.emit(_('[success] Origin set ...'))
  4579. self.plotcanvas.fit_view()
  4580. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  4581. self.should_we_save = True
  4582. def on_selectall(self):
  4583. self.report_usage("on_selectall()")
  4584. # delete the possible selection box around a possible selected object
  4585. self.delete_selection_shape()
  4586. for name in self.collection.get_names():
  4587. self.collection.set_active(name)
  4588. curr_sel_obj = self.collection.get_by_name(name)
  4589. # create the selection box around the selected object
  4590. if self.defaults['global_selection_shape'] is True:
  4591. self.draw_selection_shape(curr_sel_obj)
  4592. def on_preferences(self):
  4593. # add the tab if it was closed
  4594. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4595. # delete the absolute and relative position and messages in the infobar
  4596. self.ui.position_label.setText("")
  4597. self.ui.rel_position_label.setText("")
  4598. # Switch plot_area to preferences page
  4599. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4600. self.ui.show()
  4601. # this disconnect() is done so the slot will be connected only once
  4602. try:
  4603. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  4604. except (TypeError, AttributeError):
  4605. pass
  4606. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  4607. # detect changes in the preferences
  4608. for idx in range(self.ui.pref_tab_area.count()):
  4609. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4610. try:
  4611. try:
  4612. tb.textEdited.disconnect(self.on_preferences_edited)
  4613. except (TypeError, AttributeError):
  4614. pass
  4615. tb.textEdited.connect(self.on_preferences_edited)
  4616. except AttributeError:
  4617. pass
  4618. try:
  4619. try:
  4620. tb.modificationChanged.disconnect(self.on_preferences_edited)
  4621. except (TypeError, AttributeError):
  4622. pass
  4623. tb.modificationChanged.connect(self.on_preferences_edited)
  4624. except AttributeError:
  4625. pass
  4626. try:
  4627. try:
  4628. tb.toggled.disconnect(self.on_preferences_edited)
  4629. except (TypeError, AttributeError):
  4630. pass
  4631. tb.toggled.connect(self.on_preferences_edited)
  4632. except AttributeError:
  4633. pass
  4634. try:
  4635. try:
  4636. tb.valueChanged.disconnect(self.on_preferences_edited)
  4637. except (TypeError, AttributeError):
  4638. pass
  4639. tb.valueChanged.connect(self.on_preferences_edited)
  4640. except AttributeError:
  4641. pass
  4642. try:
  4643. try:
  4644. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  4645. except (TypeError, AttributeError):
  4646. pass
  4647. tb.currentIndexChanged.connect(self.on_preferences_edited)
  4648. except AttributeError:
  4649. pass
  4650. def on_preferences_edited(self):
  4651. self.inform.emit(_("[WARNING_NOTCL] Preferences edited but not saved."))
  4652. self.preferences_changed_flag = True
  4653. def on_preferences_closed(self):
  4654. # disconnect
  4655. for idx in range(self.ui.pref_tab_area.count()):
  4656. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4657. try:
  4658. tb.textEdited.disconnect(self.on_preferences_edited)
  4659. except (TypeError, AttributeError):
  4660. pass
  4661. try:
  4662. tb.modificationChanged.disconnect(self.on_preferences_edited)
  4663. except (TypeError, AttributeError):
  4664. pass
  4665. try:
  4666. tb.toggled.disconnect(self.on_preferences_edited)
  4667. except (TypeError, AttributeError):
  4668. pass
  4669. try:
  4670. tb.valueChanged.disconnect(self.on_preferences_edited)
  4671. except (TypeError, AttributeError):
  4672. pass
  4673. try:
  4674. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  4675. except (TypeError, AttributeError):
  4676. pass
  4677. if self.preferences_changed_flag is True:
  4678. msgbox = QtWidgets.QMessageBox()
  4679. msgbox.setText(_("One or more values are changed.\n"
  4680. "Do you want to save the Preferences?"))
  4681. msgbox.setWindowTitle(_("Save Preferences"))
  4682. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4683. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4684. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4685. msgbox.setDefaultButton(bt_yes)
  4686. msgbox.exec_()
  4687. response = msgbox.clickedButton()
  4688. if response == bt_yes:
  4689. self.on_save_button()
  4690. self.inform.emit(_("[success] Preferences saved."))
  4691. else:
  4692. self.preferences_changed_flag = False
  4693. return
  4694. def on_flipy(self):
  4695. self.report_usage("on_flipy()")
  4696. obj_list = self.collection.get_selected()
  4697. xminlist = []
  4698. yminlist = []
  4699. xmaxlist = []
  4700. ymaxlist = []
  4701. if not obj_list:
  4702. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  4703. else:
  4704. try:
  4705. # first get a bounding box to fit all
  4706. for obj in obj_list:
  4707. xmin, ymin, xmax, ymax = obj.bounds()
  4708. xminlist.append(xmin)
  4709. yminlist.append(ymin)
  4710. xmaxlist.append(xmax)
  4711. ymaxlist.append(ymax)
  4712. # get the minimum x,y and maximum x,y for all objects selected
  4713. xminimal = min(xminlist)
  4714. yminimal = min(yminlist)
  4715. xmaximal = max(xmaxlist)
  4716. ymaximal = max(ymaxlist)
  4717. px = 0.5 * (xminimal + xmaximal)
  4718. py = 0.5 * (yminimal + ymaximal)
  4719. # execute mirroring
  4720. for obj in obj_list:
  4721. obj.mirror('X', [px, py])
  4722. obj.plot()
  4723. self.object_changed.emit(obj)
  4724. self.inform.emit(_("[success] Flip on Y axis done."))
  4725. except Exception as e:
  4726. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4727. return
  4728. def on_flipx(self):
  4729. self.report_usage("on_flipx()")
  4730. obj_list = self.collection.get_selected()
  4731. xminlist = []
  4732. yminlist = []
  4733. xmaxlist = []
  4734. ymaxlist = []
  4735. if not obj_list:
  4736. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  4737. else:
  4738. try:
  4739. # first get a bounding box to fit all
  4740. for obj in obj_list:
  4741. xmin, ymin, xmax, ymax = obj.bounds()
  4742. xminlist.append(xmin)
  4743. yminlist.append(ymin)
  4744. xmaxlist.append(xmax)
  4745. ymaxlist.append(ymax)
  4746. # get the minimum x,y and maximum x,y for all objects selected
  4747. xminimal = min(xminlist)
  4748. yminimal = min(yminlist)
  4749. xmaximal = max(xmaxlist)
  4750. ymaximal = max(ymaxlist)
  4751. px = 0.5 * (xminimal + xmaximal)
  4752. py = 0.5 * (yminimal + ymaximal)
  4753. # execute mirroring
  4754. for obj in obj_list:
  4755. obj.mirror('Y', [px, py])
  4756. obj.plot()
  4757. self.object_changed.emit(obj)
  4758. self.inform.emit(_("[success] Flip on X axis done."))
  4759. except Exception as e:
  4760. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4761. return
  4762. def on_rotate(self, silent=False, preset=None):
  4763. self.report_usage("on_rotate()")
  4764. obj_list = self.collection.get_selected()
  4765. xminlist = []
  4766. yminlist = []
  4767. xmaxlist = []
  4768. ymaxlist = []
  4769. if not obj_list:
  4770. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  4771. else:
  4772. if silent is False:
  4773. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4774. min=-360, max=360, decimals=4,
  4775. init_val=float(self.defaults['tools_transform_rotate']))
  4776. num, ok = rotatebox.get_value()
  4777. else:
  4778. num = preset
  4779. ok = True
  4780. if ok:
  4781. try:
  4782. # first get a bounding box to fit all
  4783. for obj in obj_list:
  4784. xmin, ymin, xmax, ymax = obj.bounds()
  4785. xminlist.append(xmin)
  4786. yminlist.append(ymin)
  4787. xmaxlist.append(xmax)
  4788. ymaxlist.append(ymax)
  4789. # get the minimum x,y and maximum x,y for all objects selected
  4790. xminimal = min(xminlist)
  4791. yminimal = min(yminlist)
  4792. xmaximal = max(xmaxlist)
  4793. ymaximal = max(ymaxlist)
  4794. px = 0.5 * (xminimal + xmaximal)
  4795. py = 0.5 * (yminimal + ymaximal)
  4796. for sel_obj in obj_list:
  4797. sel_obj.rotate(-float(num), point=(px, py))
  4798. sel_obj.plot()
  4799. self.object_changed.emit(sel_obj)
  4800. self.inform.emit(_("[success] Rotation done."))
  4801. except Exception as e:
  4802. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  4803. return
  4804. def on_skewx(self):
  4805. self.report_usage("on_skewx()")
  4806. obj_list = self.collection.get_selected()
  4807. xminlist = []
  4808. yminlist = []
  4809. if not obj_list:
  4810. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  4811. else:
  4812. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4813. min=-360, max=360, decimals=4,
  4814. init_val=float(self.defaults['tools_transform_skew_x']))
  4815. num, ok = skewxbox.get_value()
  4816. if ok:
  4817. # first get a bounding box to fit all
  4818. for obj in obj_list:
  4819. xmin, ymin, xmax, ymax = obj.bounds()
  4820. xminlist.append(xmin)
  4821. yminlist.append(ymin)
  4822. # get the minimum x,y and maximum x,y for all objects selected
  4823. xminimal = min(xminlist)
  4824. yminimal = min(yminlist)
  4825. for obj in obj_list:
  4826. obj.skew(num, 0, point=(xminimal, yminimal))
  4827. obj.plot()
  4828. self.object_changed.emit(obj)
  4829. self.inform.emit(_("[success] Skew on X axis done."))
  4830. def on_skewy(self):
  4831. self.report_usage("on_skewy()")
  4832. obj_list = self.collection.get_selected()
  4833. xminlist = []
  4834. yminlist = []
  4835. if not obj_list:
  4836. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  4837. else:
  4838. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4839. min=-360, max=360, decimals=4,
  4840. init_val=float(self.defaults['tools_transform_skew_y']))
  4841. num, ok = skewybox.get_value()
  4842. if ok:
  4843. # first get a bounding box to fit all
  4844. for obj in obj_list:
  4845. xmin, ymin, xmax, ymax = obj.bounds()
  4846. xminlist.append(xmin)
  4847. yminlist.append(ymin)
  4848. # get the minimum x,y and maximum x,y for all objects selected
  4849. xminimal = min(xminlist)
  4850. yminimal = min(yminlist)
  4851. for obj in obj_list:
  4852. obj.skew(0, num, point=(xminimal, yminimal))
  4853. obj.plot()
  4854. self.object_changed.emit(obj)
  4855. self.inform.emit(_("[success] Skew on Y axis done."))
  4856. def on_plots_updated(self):
  4857. """
  4858. Callback used to report when the plots have changed.
  4859. Adjust axes and zooms to fit.
  4860. :return: None
  4861. """
  4862. self.plotcanvas.update() # TODO: Need update canvas?
  4863. self.on_zoom_fit(None)
  4864. self.collection.update_view()
  4865. # self.inform.emit(_("Plots updated ..."))
  4866. # TODO: Rework toolbar 'clear', 'replot' functions
  4867. def on_toolbar_replot(self):
  4868. """
  4869. Callback for toolbar button. Re-plots all objects.
  4870. :return: None
  4871. """
  4872. self.report_usage("on_toolbar_replot")
  4873. self.log.debug("on_toolbar_replot()")
  4874. try:
  4875. self.collection.get_active().read_form()
  4876. except AttributeError:
  4877. self.log.debug("on_toolbar_replot(): AttributeError")
  4878. pass
  4879. self.plot_all()
  4880. def on_row_activated(self, index):
  4881. if index.isValid():
  4882. if index.internalPointer().parent_item != self.collection.root_item:
  4883. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4884. self.collection.on_item_activated(index)
  4885. def grid_status(self):
  4886. if self.ui.grid_snap_btn.isChecked():
  4887. return True
  4888. else:
  4889. return False
  4890. def populate_cmenu_grids(self):
  4891. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4892. self.ui.cmenu_gridmenu.clear()
  4893. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4894. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  4895. grid_toggle.setCheckable(True)
  4896. if self.grid_status() == True:
  4897. grid_toggle.setChecked(True)
  4898. else:
  4899. grid_toggle.setChecked(False)
  4900. self.ui.cmenu_gridmenu.addSeparator()
  4901. for grid in sorted_list:
  4902. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  4903. action.triggered.connect(self.set_grid)
  4904. self.ui.cmenu_gridmenu.addSeparator()
  4905. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  4906. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  4907. grid_add.triggered.connect(self.on_grid_add)
  4908. grid_delete.triggered.connect(self.on_grid_delete)
  4909. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4910. def set_grid(self):
  4911. self.ui.grid_gap_x_entry.setText(self.sender().text())
  4912. self.ui.grid_gap_y_entry.setText(self.sender().text())
  4913. def on_grid_add(self):
  4914. # ## Current application units in lower Case
  4915. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4916. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4917. text=_('Enter a Grid Value:'),
  4918. min=0.0000, max=99.9999, decimals=4)
  4919. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  4920. val, ok = grid_add_popup.get_value()
  4921. if ok:
  4922. if float(val) == 0:
  4923. self.inform.emit(
  4924. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4925. return
  4926. else:
  4927. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4928. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4929. self.inform.emit(
  4930. _("[success] New Grid added ..."))
  4931. else:
  4932. self.inform.emit(
  4933. _("[WARNING_NOTCL] Grid already exists ..."))
  4934. else:
  4935. self.inform.emit(
  4936. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  4937. def on_grid_delete(self):
  4938. # ## Current application units in lower Case
  4939. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4940. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4941. text='Enter a Grid Value:',
  4942. min=0.0000, max=99.9999, decimals=4)
  4943. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  4944. val, ok = grid_del_popup.get_value()
  4945. if ok:
  4946. if float(val) == 0:
  4947. self.inform.emit(
  4948. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4949. return
  4950. else:
  4951. try:
  4952. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4953. except ValueError:
  4954. self.inform.emit(
  4955. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  4956. return
  4957. self.inform.emit(
  4958. _("[success] Grid Value deleted ..."))
  4959. else:
  4960. self.inform.emit(
  4961. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  4962. def on_shortcut_list(self):
  4963. self.report_usage("on_shortcut_list()")
  4964. # add the tab if it was closed
  4965. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4966. # delete the absolute and relative position and messages in the infobar
  4967. self.ui.position_label.setText("")
  4968. self.ui.rel_position_label.setText("")
  4969. # Switch plot_area to preferences page
  4970. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4971. self.ui.show()
  4972. def on_select_tab(self, name):
  4973. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4974. if self.ui.splitter.sizes()[0] == 0:
  4975. self.ui.splitter.setSizes([1, 1])
  4976. else:
  4977. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4978. self.ui.splitter.setSizes([0, 1])
  4979. if name == 'project':
  4980. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4981. elif name == 'selected':
  4982. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4983. elif name == 'tool':
  4984. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4985. def on_copy_name(self):
  4986. self.report_usage("on_copy_name()")
  4987. obj = self.collection.get_active()
  4988. try:
  4989. name = obj.options["name"]
  4990. except AttributeError:
  4991. log.debug("on_copy_name() --> No object selected to copy it's name")
  4992. self.inform.emit(_("[WARNING_NOTCL] No object selected to copy it's name"))
  4993. return
  4994. self.clipboard.setText(name)
  4995. self.inform.emit(_("Name copied on clipboard ..."))
  4996. def on_mouse_click_over_plot(self, event):
  4997. """
  4998. Default actions are:
  4999. :param event: Contains information about the event, like which button
  5000. was clicked, the pixel coordinates and the axes coordinates.
  5001. :return: None
  5002. """
  5003. self.pos = []
  5004. # So it can receive key presses
  5005. self.plotcanvas.native.setFocus()
  5006. # Set the mouse button for panning
  5007. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  5008. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5009. if self.grid_status() == True:
  5010. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5011. self.app_cursor.enabled = True
  5012. else:
  5013. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5014. self.app_cursor.enabled = False
  5015. try:
  5016. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5017. if event.button == 1:
  5018. # Reset here the relative coordinates so there is a new reference on the click position
  5019. if self.rel_point1 is None:
  5020. self.rel_point1 = self.pos
  5021. else:
  5022. self.rel_point2 = copy(self.rel_point1)
  5023. self.rel_point1 = self.pos
  5024. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5025. if modifiers == QtCore.Qt.ShiftModifier:
  5026. # do not auto open the Project Tab
  5027. self.click_noproject = True
  5028. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  5029. self.inform.emit(_("[success] Coordinates copied to clipboard."))
  5030. return
  5031. self.on_mouse_move_over_plot(event, origin_click=True)
  5032. except Exception as e:
  5033. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5034. def on_double_click_over_plot(self, event):
  5035. self.doubleclick = True
  5036. def on_mouse_move_over_plot(self, event, origin_click=None):
  5037. """
  5038. Callback for the mouse motion event over the plot.
  5039. :param event: Contains information about the event.
  5040. :param origin_click
  5041. :return: None
  5042. """
  5043. # So it can receive key presses
  5044. self.plotcanvas.native.setFocus()
  5045. self.pos_jump = event.pos
  5046. self.ui.popMenu.mouse_is_panning = False
  5047. if origin_click != True:
  5048. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5049. if event.button == 2 and event.is_dragging == 1:
  5050. self.ui.popMenu.mouse_is_panning = True
  5051. return
  5052. if self.rel_point1 is not None:
  5053. try: # May fail in case mouse not within axes
  5054. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5055. if self.grid_status() == True:
  5056. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5057. self.app_cursor.enabled = True
  5058. # Update cursor
  5059. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  5060. else:
  5061. pos = (pos_canvas[0], pos_canvas[1])
  5062. self.app_cursor.enabled = False
  5063. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5064. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5065. dx = pos[0] - self.rel_point1[0]
  5066. dy = pos[1] - self.rel_point1[1]
  5067. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5068. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5069. self.mouse = [pos[0], pos[1]]
  5070. # if the mouse is moved and the LMB is clicked then the action is a selection
  5071. if event.is_dragging == 1 and event.button == 1:
  5072. self.delete_selection_shape()
  5073. if dx < 0:
  5074. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5075. face_color=self.defaults['global_alt_sel_fill'])
  5076. self.selection_type = False
  5077. else:
  5078. self.draw_moving_selection_shape(self.pos, pos)
  5079. self.selection_type = True
  5080. # hover effect - enabled in Preferences -> General -> GUI Settings
  5081. if self.defaults['global_hover']:
  5082. for obj in self.collection.get_list():
  5083. try:
  5084. # select the object(s) only if it is enabled (plotted)
  5085. if obj.options['plot']:
  5086. if obj not in self.collection.get_selected():
  5087. poly_obj = Polygon(
  5088. [(obj.options['xmin'], obj.options['ymin']),
  5089. (obj.options['xmax'], obj.options['ymin']),
  5090. (obj.options['xmax'], obj.options['ymax']),
  5091. (obj.options['xmin'], obj.options['ymax'])]
  5092. )
  5093. if Point(pos).within(poly_obj):
  5094. if obj.isHovering is False:
  5095. obj.isHovering = True
  5096. obj.notHovering = True
  5097. # create the selection box around the selected object
  5098. self.draw_hover_shape(obj, color='#d1e0e0')
  5099. else:
  5100. if obj.notHovering is True:
  5101. obj.notHovering = False
  5102. obj.isHovering = False
  5103. self.delete_hover_shape()
  5104. except:
  5105. # the Exception here will happen if we try to select on screen and we have an
  5106. # newly (and empty) just created Geometry or Excellon object that do not have the
  5107. # xmin, xmax, ymin, ymax options.
  5108. # In this case poly_obj creation (see above) will fail
  5109. pass
  5110. except:
  5111. self.ui.position_label.setText("")
  5112. self.ui.rel_position_label.setText("")
  5113. self.mouse = None
  5114. def on_mouse_click_release_over_plot(self, event):
  5115. """
  5116. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5117. and has been registered in ''self.__init__()''.
  5118. :param event: contains information about the event.
  5119. :return:
  5120. """
  5121. pos = 0, 0
  5122. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5123. if self.grid_status() == True:
  5124. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5125. else:
  5126. pos = (pos_canvas[0], pos_canvas[1])
  5127. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5128. # canvas menu
  5129. if event.button == 2: # right click
  5130. if self.ui.popMenu.mouse_is_panning is False:
  5131. self.cursor = QtGui.QCursor()
  5132. self.populate_cmenu_grids()
  5133. self.ui.popMenu.popup(self.cursor.pos())
  5134. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5135. # selection and then select a type of selection ("enclosing" or "touching")
  5136. try:
  5137. if event.button == 1: # left click
  5138. if self.doubleclick is True:
  5139. self.doubleclick = False
  5140. if self.collection.get_selected():
  5141. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5142. if self.ui.splitter.sizes()[0] == 0:
  5143. self.ui.splitter.setSizes([1, 1])
  5144. # delete the selection shape(S) as it may be in the way
  5145. self.delete_selection_shape()
  5146. self.delete_hover_shape()
  5147. else:
  5148. if self.selection_type is not None:
  5149. self.selection_area_handler(self.pos, pos, self.selection_type)
  5150. self.selection_type = None
  5151. else:
  5152. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5153. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5154. # deselect, and if it's not selected then it will be selected
  5155. if modifiers == QtCore.Qt.ControlModifier:
  5156. # If there is no active command (self.command_active is None) then we check if we clicked
  5157. # on a object by checking the bounding limits against mouse click position
  5158. if self.command_active is None:
  5159. self.select_objects(key='CTRL')
  5160. self.delete_hover_shape()
  5161. elif modifiers == QtCore.Qt.ShiftModifier:
  5162. # if SHIFT was pressed and LMB is clicked then we have a coordinates copy to clipboard
  5163. # therefore things should stay as they are
  5164. pass
  5165. else:
  5166. # If there is no active command (self.command_active is None) then we check if we clicked
  5167. # on a object by checking the bounding limits against mouse click position
  5168. if self.command_active is None:
  5169. self.select_objects()
  5170. self.delete_hover_shape()
  5171. except Exception as e:
  5172. log.warning("Error: %s" % str(e))
  5173. return
  5174. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5175. """
  5176. :param start_pos: mouse position when the selection LMB click was done
  5177. :param end_pos: mouse position when the left mouse button is released
  5178. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5179. :return:
  5180. """
  5181. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5182. self.delete_selection_shape()
  5183. for obj in self.collection.get_list():
  5184. try:
  5185. # select the object(s) only if it is enabled (plotted)
  5186. if obj.options['plot']:
  5187. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5188. (obj.options['xmax'], obj.options['ymin']),
  5189. (obj.options['xmax'], obj.options['ymax']),
  5190. (obj.options['xmin'], obj.options['ymax'])])
  5191. if sel_type is True:
  5192. if poly_obj.within(poly_selection):
  5193. # create the selection box around the selected object
  5194. if self.defaults['global_selection_shape'] is True:
  5195. self.draw_selection_shape(obj)
  5196. self.collection.set_active(obj.options['name'])
  5197. else:
  5198. if poly_selection.intersects(poly_obj):
  5199. # create the selection box around the selected object
  5200. if self.defaults['global_selection_shape'] is True:
  5201. self.draw_selection_shape(obj)
  5202. self.collection.set_active(obj.options['name'])
  5203. except Exception as e:
  5204. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5205. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5206. # In this case poly_obj creation (see above) will fail
  5207. log.debug("App.selection_area_handler() --> %s" % str(e))
  5208. def select_objects(self, key=None):
  5209. # list where we store the overlapped objects under our mouse left click position
  5210. objects_under_the_click_list = []
  5211. # Populate the list with the overlapped objects on the click position
  5212. curr_x, curr_y = self.pos
  5213. for obj in self.all_objects_list:
  5214. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5215. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5216. if obj.options['name'] not in objects_under_the_click_list:
  5217. if obj.options['plot']:
  5218. # add objects to the objects_under_the_click list only if the object is plotted
  5219. # (active and not disabled)
  5220. objects_under_the_click_list.append(obj.options['name'])
  5221. try:
  5222. # If there is no element in the overlapped objects list then make everyone inactive
  5223. # because we selected "nothing"
  5224. if not objects_under_the_click_list:
  5225. self.collection.set_all_inactive()
  5226. # delete the possible selection box around a possible selected object
  5227. self.delete_selection_shape()
  5228. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5229. # only when working on App
  5230. if self.call_source == 'app':
  5231. if self.click_noproject is False:
  5232. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5233. else:
  5234. # restore auto open the Project Tab
  5235. self.click_noproject = False
  5236. # delete any text in the status bar, implicitly the last object name that was selected
  5237. self.inform.emit("")
  5238. else:
  5239. self.call_source = 'app'
  5240. else:
  5241. # case when there is only an object under the click and we toggle it
  5242. if len(objects_under_the_click_list) == 1:
  5243. if self.collection.get_active() is None:
  5244. self.collection.set_active(objects_under_the_click_list[0])
  5245. # create the selection box around the selected object
  5246. curr_sel_obj = self.collection.get_active()
  5247. if self.defaults['global_selection_shape'] is True:
  5248. self.draw_selection_shape(curr_sel_obj)
  5249. # self.inform.emit('[selected] %s: %s selected' %
  5250. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5251. if curr_sel_obj.kind == 'gerber':
  5252. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5253. color='green', name=str(curr_sel_obj.options['name'])))
  5254. elif curr_sel_obj.kind == 'excellon':
  5255. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5256. color='brown', name=str(curr_sel_obj.options['name'])))
  5257. elif curr_sel_obj.kind == 'cncjob':
  5258. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5259. color='blue', name=str(curr_sel_obj.options['name'])))
  5260. elif curr_sel_obj.kind == 'geometry':
  5261. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5262. color='red', name=str(curr_sel_obj.options['name'])))
  5263. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  5264. self.collection.set_all_inactive()
  5265. self.delete_selection_shape()
  5266. self.collection.set_active(objects_under_the_click_list[0])
  5267. # create the selection box around the selected object
  5268. curr_sel_obj = self.collection.get_active()
  5269. if self.defaults['global_selection_shape'] is True:
  5270. self.draw_selection_shape(curr_sel_obj)
  5271. # self.inform.emit('[selected] %s: %s selected' %
  5272. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5273. if curr_sel_obj.kind == 'gerber':
  5274. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5275. color='green', name=str(curr_sel_obj.options['name'])))
  5276. elif curr_sel_obj.kind == 'excellon':
  5277. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5278. color='brown', name=str(curr_sel_obj.options['name'])))
  5279. elif curr_sel_obj.kind == 'cncjob':
  5280. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5281. color='blue', name=str(curr_sel_obj.options['name'])))
  5282. elif curr_sel_obj.kind == 'geometry':
  5283. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5284. color='red', name=str(curr_sel_obj.options['name'])))
  5285. else:
  5286. self.collection.set_all_inactive()
  5287. self.delete_selection_shape()
  5288. if self.call_source == 'app':
  5289. # delete any text in the status bar, implicitly the last object name that was selected
  5290. self.inform.emit("")
  5291. else:
  5292. self.call_source = 'app'
  5293. else:
  5294. # If there is no selected object
  5295. # make active the first element of the overlapped objects list
  5296. if self.collection.get_active() is None:
  5297. self.collection.set_active(objects_under_the_click_list[0])
  5298. name_sel_obj = self.collection.get_active().options['name']
  5299. # In case that there is a selected object but it is not in the overlapped object list
  5300. # make that object inactive and activate the first element in the overlapped object list
  5301. if name_sel_obj not in objects_under_the_click_list:
  5302. self.collection.set_inactive(name_sel_obj)
  5303. name_sel_obj = objects_under_the_click_list[0]
  5304. self.collection.set_active(name_sel_obj)
  5305. else:
  5306. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  5307. self.collection.set_all_inactive()
  5308. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  5309. len(objects_under_the_click_list)])
  5310. curr_sel_obj = self.collection.get_active()
  5311. # delete the possible selection box around a possible selected object
  5312. self.delete_selection_shape()
  5313. # create the selection box around the selected object
  5314. if self.defaults['global_selection_shape'] is True:
  5315. self.draw_selection_shape(curr_sel_obj)
  5316. # self.inform.emit('[selected] %s: %s selected' %
  5317. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5318. if curr_sel_obj.kind == 'gerber':
  5319. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5320. color='green', name=str(curr_sel_obj.options['name'])))
  5321. elif curr_sel_obj.kind == 'excellon':
  5322. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5323. color='brown', name=str(curr_sel_obj.options['name'])))
  5324. elif curr_sel_obj.kind == 'cncjob':
  5325. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5326. color='blue', name=str(curr_sel_obj.options['name'])))
  5327. elif curr_sel_obj.kind == 'geometry':
  5328. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5329. color='red', name=str(curr_sel_obj.options['name'])))
  5330. # for obj in self.collection.get_list():
  5331. # obj.plot()
  5332. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  5333. # TODO: on selected objects change the object colors and do not draw the selection box
  5334. # self.plotcanvas.update() # this updates the canvas
  5335. except Exception as e:
  5336. log.error("[ERROR] Something went bad. %s" % str(e))
  5337. return
  5338. def delete_hover_shape(self):
  5339. self.hover_shapes.clear()
  5340. self.hover_shapes.redraw()
  5341. def draw_hover_shape(self, sel_obj, color=None):
  5342. """
  5343. :param sel_obj: the object for which the hover shape must be drawn
  5344. :return:
  5345. """
  5346. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5347. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5348. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5349. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5350. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5351. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5352. hover_rect = hover_rect.buffer(-0.1)
  5353. hover_rect = hover_rect.buffer(0.2)
  5354. else:
  5355. hover_rect = hover_rect.buffer(-0.00393)
  5356. hover_rect = hover_rect.buffer(0.00787)
  5357. if color:
  5358. face = Color(color)
  5359. face.alpha = 0.2
  5360. outline = Color(color, alpha=0.8)
  5361. else:
  5362. face = Color(self.defaults['global_sel_fill'])
  5363. face.alpha = 0.2
  5364. outline = self.defaults['global_sel_line']
  5365. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5366. def delete_selection_shape(self):
  5367. self.move_tool.sel_shapes.clear()
  5368. self.move_tool.sel_shapes.redraw()
  5369. def draw_selection_shape(self, sel_obj, color=None):
  5370. """
  5371. :param sel_obj: the object for which the selection shape must be drawn
  5372. :return:
  5373. """
  5374. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5375. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5376. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5377. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5378. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5379. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5380. sel_rect = sel_rect.buffer(-0.1)
  5381. sel_rect = sel_rect.buffer(0.2)
  5382. else:
  5383. sel_rect = sel_rect.buffer(-0.00393)
  5384. sel_rect = sel_rect.buffer(0.00787)
  5385. if color:
  5386. face = Color(color, alpha=0.2)
  5387. outline = Color(color, alpha=0.8)
  5388. else:
  5389. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  5390. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  5391. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5392. color=outline,
  5393. face_color=face,
  5394. update=True,
  5395. layer=0,
  5396. tolerance=None))
  5397. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5398. """
  5399. :param old_coords: old coordinates
  5400. :param coords: new coordinates
  5401. :return:
  5402. """
  5403. if 'color' in kwargs:
  5404. color = kwargs['color']
  5405. else:
  5406. color = self.defaults['global_sel_line']
  5407. if 'face_color' in kwargs:
  5408. face_color = kwargs['face_color']
  5409. else:
  5410. face_color = self.defaults['global_sel_fill']
  5411. if 'face_alpha' in kwargs:
  5412. face_alpha = kwargs['face_alpha']
  5413. else:
  5414. face_alpha = 0.3
  5415. x0, y0 = old_coords
  5416. x1, y1 = coords
  5417. pt1 = (x0, y0)
  5418. pt2 = (x1, y0)
  5419. pt3 = (x1, y1)
  5420. pt4 = (x0, y1)
  5421. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5422. color_t = Color(face_color)
  5423. color_t.alpha = face_alpha
  5424. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5425. layer=0, tolerance=None)
  5426. def on_file_new_click(self):
  5427. if self.collection.get_list() and self.should_we_save:
  5428. msgbox = QtWidgets.QMessageBox()
  5429. # msgbox.setText("<B>Save changes ...</B>")
  5430. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5431. "Creating a New project will delete them.\n"
  5432. "Do you want to Save the project?"))
  5433. msgbox.setWindowTitle(_("Save changes"))
  5434. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5435. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5436. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5437. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5438. msgbox.setDefaultButton(bt_yes)
  5439. msgbox.exec_()
  5440. response = msgbox.clickedButton()
  5441. if response == bt_yes:
  5442. self.on_file_saveprojectas()
  5443. elif response == bt_cancel:
  5444. return
  5445. elif response == bt_no:
  5446. self.on_file_new()
  5447. else:
  5448. self.on_file_new()
  5449. self.inform.emit(_("[success] New Project created..."))
  5450. def on_file_new(self):
  5451. """
  5452. Callback for menu item File->New. Returns the application to its
  5453. startup state. This method is thread-safe.
  5454. :return: None
  5455. """
  5456. self.report_usage("on_file_new")
  5457. # Remove everything from memory
  5458. App.log.debug("on_file_new()")
  5459. if self.call_source != 'app':
  5460. self.editor2object(cleanup=True)
  5461. # ## EDITOR section
  5462. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  5463. self.exc_editor = FlatCAMExcEditor(self)
  5464. self.grb_editor = FlatCAMGrbEditor(self)
  5465. # Clear pool
  5466. self.clear_pool()
  5467. for obj in self.collection.get_list():
  5468. # delete shapes left drawn from mark shape_collections, if any
  5469. if isinstance(obj, FlatCAMGerber):
  5470. try:
  5471. obj.mark_shapes.enabled = False
  5472. obj.mark_shapes.clear(update=True)
  5473. except AttributeError:
  5474. pass
  5475. # also delete annotation shapes, if any
  5476. elif isinstance(obj, FlatCAMCNCjob):
  5477. try:
  5478. obj.annotation.enabled = False
  5479. obj.annotation.clear(update=True)
  5480. except AttributeError:
  5481. pass
  5482. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5483. self.init_tcl()
  5484. self.delete_selection_shape()
  5485. self.collection.delete_all()
  5486. self.setup_component_editor()
  5487. # Clear project filename
  5488. self.project_filename = None
  5489. # Load the application defaults
  5490. self.load_defaults(filename='current_defaults')
  5491. # Re-fresh project options
  5492. self.on_options_app2project()
  5493. # Init Tools
  5494. self.init_tools()
  5495. # Close any Tabs opened in the Plot Tab Area section
  5496. for index in range(self.ui.plot_tab_area.count()):
  5497. self.ui.plot_tab_area.closeTab(index)
  5498. # for whatever reason previous command does not close the last tab so I do it manually
  5499. self.ui.plot_tab_area.closeTab(0)
  5500. # # And then add again the Plot Area
  5501. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  5502. self.ui.plot_tab_area.protectTab(0)
  5503. # take the focus of the Notebook on Project Tab.
  5504. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5505. self.set_ui_title(name=_("New Project - Not saved"))
  5506. def obj_properties(self):
  5507. self.report_usage("obj_properties()")
  5508. self.properties_tool.run(toggle=False)
  5509. def on_project_context_save(self):
  5510. obj = self.collection.get_active()
  5511. if type(obj) == FlatCAMGeometry:
  5512. self.on_file_exportdxf()
  5513. elif type(obj) == FlatCAMExcellon:
  5514. self.on_file_saveexcellon()
  5515. elif type(obj) == FlatCAMCNCjob:
  5516. obj.on_exportgcode_button_click()
  5517. elif type(obj) == FlatCAMGerber:
  5518. self.on_file_savegerber()
  5519. def obj_move(self):
  5520. self.report_usage("obj_move()")
  5521. self.move_tool.run(toggle=False)
  5522. def on_fileopengerber(self):
  5523. """
  5524. File menu callback for opening a Gerber.
  5525. :return: None
  5526. """
  5527. self.report_usage("on_fileopengerber")
  5528. App.log.debug("on_fileopengerber()")
  5529. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5530. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5531. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  5532. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5533. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5534. "*.mil);;" \
  5535. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5536. "Allegro Files (*.art);;" \
  5537. "Mentor Files (*.pho *.gdo);;" \
  5538. "All Files (*.*)"
  5539. try:
  5540. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5541. directory=self.get_last_folder(), filter=_filter_)
  5542. except TypeError:
  5543. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5544. filenames = [str(filename) for filename in filenames]
  5545. if len(filenames) == 0:
  5546. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  5547. else:
  5548. for filename in filenames:
  5549. if filename != '':
  5550. self.worker_task.emit({'fcn': self.open_gerber,
  5551. 'params': [filename]})
  5552. def on_fileopenexcellon(self):
  5553. """
  5554. File menu callback for opening an Excellon file.
  5555. :return: None
  5556. """
  5557. self.report_usage("on_fileopenexcellon")
  5558. App.log.debug("on_fileopenexcellon()")
  5559. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5560. "All Files (*.*)"
  5561. try:
  5562. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5563. directory=self.get_last_folder(), filter=_filter_)
  5564. except TypeError:
  5565. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5566. filenames = [str(filename) for filename in filenames]
  5567. if len(filenames) == 0:
  5568. self.inform.emit(_("[WARNING_NOTCL] Open Excellon cancelled."))
  5569. else:
  5570. for filename in filenames:
  5571. if filename != '':
  5572. self.worker_task.emit({'fcn': self.open_excellon,
  5573. 'params': [filename]})
  5574. def on_fileopengcode(self):
  5575. """
  5576. File menu call back for opening gcode.
  5577. :return: None
  5578. """
  5579. self.report_usage("on_fileopengcode")
  5580. App.log.debug("on_fileopengcode()")
  5581. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5582. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5583. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  5584. "All Files (*.*)"
  5585. try:
  5586. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5587. directory=self.get_last_folder(), filter=_filter_)
  5588. except TypeError:
  5589. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5590. filenames = [str(filename) for filename in filenames]
  5591. if len(filenames) == 0:
  5592. self.inform.emit(_("[WARNING_NOTCL] Open G-Code cancelled."))
  5593. else:
  5594. for filename in filenames:
  5595. if filename != '':
  5596. self.worker_task.emit({'fcn': self.open_gcode,
  5597. 'params': [filename]})
  5598. def on_file_openproject(self):
  5599. """
  5600. File menu callback for opening a project.
  5601. :return: None
  5602. """
  5603. self.report_usage("on_file_openproject")
  5604. App.log.debug("on_file_openproject()")
  5605. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5606. try:
  5607. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5608. directory=self.get_last_folder(), filter=_filter_)
  5609. except TypeError:
  5610. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5611. # The Qt methods above will return a QString which can cause problems later.
  5612. # So far json.dump() will fail to serialize it.
  5613. # TODO: Improve the serialization methods and remove this fix.
  5614. filename = str(filename)
  5615. if filename == "":
  5616. self.inform.emit(_("[WARNING_NOTCL] Open Project cancelled."))
  5617. else:
  5618. # self.worker_task.emit({'fcn': self.open_project,
  5619. # 'params': [filename]})
  5620. # The above was failing because open_project() is not
  5621. # thread safe. The new_project()
  5622. self.open_project(filename)
  5623. def on_file_openconfig(self):
  5624. """
  5625. File menu callback for opening a config file.
  5626. :return: None
  5627. """
  5628. self.report_usage("on_file_openconfig")
  5629. App.log.debug("on_file_openconfig()")
  5630. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5631. try:
  5632. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5633. directory=self.data_path, filter=_filter_)
  5634. except TypeError:
  5635. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5636. filter=_filter_)
  5637. if filename == "":
  5638. self.inform.emit(_("[WARNING_NOTCL] Open Config cancelled."))
  5639. else:
  5640. self.open_config_file(filename)
  5641. def on_file_exportsvg(self):
  5642. """
  5643. Callback for menu item File->Export SVG.
  5644. :return: None
  5645. """
  5646. self.report_usage("on_file_exportsvg")
  5647. App.log.debug("on_file_exportsvg()")
  5648. obj = self.collection.get_active()
  5649. if obj is None:
  5650. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5651. msg = _("Please Select a Geometry object to export")
  5652. msgbox = QtWidgets.QMessageBox()
  5653. msgbox.setInformativeText(msg)
  5654. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5655. msgbox.setDefaultButton(bt_ok)
  5656. msgbox.exec_()
  5657. return
  5658. # Check for more compatible types and add as required
  5659. if (not isinstance(obj, FlatCAMGeometry)
  5660. and not isinstance(obj, FlatCAMGerber)
  5661. and not isinstance(obj, FlatCAMCNCjob)
  5662. and not isinstance(obj, FlatCAMExcellon)):
  5663. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  5664. msgbox = QtWidgets.QMessageBox()
  5665. msgbox.setInformativeText(msg)
  5666. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5667. msgbox.setDefaultButton(bt_ok)
  5668. msgbox.exec_()
  5669. return
  5670. name = obj.options["name"]
  5671. _filter = "SVG File (*.svg);;All Files (*.*)"
  5672. try:
  5673. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5674. caption=_("Export SVG"),
  5675. directory=self.get_last_save_folder() + '/' + str(name),
  5676. filter=_filter)
  5677. except TypeError:
  5678. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  5679. filename = str(filename)
  5680. if filename == "":
  5681. self.inform.emit(_("[WARNING_NOTCL] Export SVG cancelled."))
  5682. return
  5683. else:
  5684. self.export_svg(name, filename)
  5685. if self.defaults["global_open_style"] is False:
  5686. self.file_opened.emit("SVG", filename)
  5687. self.file_saved.emit("SVG", filename)
  5688. def on_file_exportpng(self):
  5689. self.report_usage("on_file_exportpng")
  5690. App.log.debug("on_file_exportpng()")
  5691. self.date = str(datetime.today()).rpartition('.')[0]
  5692. self.date = ''.join(c for c in self.date if c not in ':-')
  5693. self.date = self.date.replace(' ', '_')
  5694. image = _screenshot()
  5695. data = np.asarray(image)
  5696. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5697. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  5698. return
  5699. filter_ = "PNG File (*.png);;All Files (*.*)"
  5700. try:
  5701. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5702. caption=_("Export PNG Image"),
  5703. directory=self.get_last_save_folder() + '/png_' + self.date,
  5704. filter=filter_)
  5705. except TypeError:
  5706. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  5707. filename = str(filename)
  5708. if filename == "":
  5709. self.inform.emit(_("Export PNG cancelled."))
  5710. return
  5711. else:
  5712. write_png(filename, data)
  5713. if self.defaults["global_open_style"] is False:
  5714. self.file_opened.emit("png", filename)
  5715. self.file_saved.emit("png", filename)
  5716. def on_file_savegerber(self):
  5717. """
  5718. Callback for menu item File->Export Gerber.
  5719. :return: None
  5720. """
  5721. self.report_usage("on_file_savegerber")
  5722. App.log.debug("on_file_savegerber()")
  5723. obj = self.collection.get_active()
  5724. if obj is None:
  5725. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  5726. return
  5727. # Check for more compatible types and add as required
  5728. if not isinstance(obj, FlatCAMGerber):
  5729. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5730. return
  5731. name = self.collection.get_active().options["name"]
  5732. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5733. try:
  5734. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5735. caption="Save Gerber source file",
  5736. directory=self.get_last_save_folder() + '/' + name,
  5737. filter=_filter)
  5738. except TypeError:
  5739. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  5740. filename = str(filename)
  5741. if filename == "":
  5742. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  5743. return
  5744. else:
  5745. self.save_source_file(name, filename)
  5746. if self.defaults["global_open_style"] is False:
  5747. self.file_opened.emit("Gerber", filename)
  5748. self.file_saved.emit("Gerber", filename)
  5749. def on_file_saveexcellon(self):
  5750. """
  5751. Callback for menu item File->Export Gerber.
  5752. :return: None
  5753. """
  5754. self.report_usage("on_file_saveexcellon")
  5755. App.log.debug("on_file_saveexcellon()")
  5756. obj = self.collection.get_active()
  5757. if obj is None:
  5758. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  5759. return
  5760. # Check for more compatible types and add as required
  5761. if not isinstance(obj, FlatCAMExcellon):
  5762. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5763. return
  5764. name = self.collection.get_active().options["name"]
  5765. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5766. try:
  5767. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5768. caption=_("Save Excellon source file"),
  5769. directory=self.get_last_save_folder() + '/' + name,
  5770. filter=_filter)
  5771. except TypeError:
  5772. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  5773. filename = str(filename)
  5774. if filename == "":
  5775. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  5776. return
  5777. else:
  5778. self.save_source_file(name, filename)
  5779. if self.defaults["global_open_style"] is False:
  5780. self.file_opened.emit("Excellon", filename)
  5781. self.file_saved.emit("Excellon", filename)
  5782. def on_file_exportexcellon(self):
  5783. """
  5784. Callback for menu item File->Export->Excellon.
  5785. :return: None
  5786. """
  5787. self.report_usage("on_file_exportexcellon")
  5788. App.log.debug("on_file_exportexcellon()")
  5789. obj = self.collection.get_active()
  5790. if obj is None:
  5791. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  5792. return
  5793. # Check for more compatible types and add as required
  5794. if not isinstance(obj, FlatCAMExcellon):
  5795. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5796. return
  5797. name = self.collection.get_active().options["name"]
  5798. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5799. try:
  5800. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5801. caption=_("Export Excellon"),
  5802. directory=self.get_last_save_folder() + '/' + name,
  5803. filter=_filter)
  5804. except TypeError:
  5805. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  5806. filename = str(filename)
  5807. if filename == "":
  5808. self.inform.emit(_("[WARNING_NOTCL] Export Excellon cancelled."))
  5809. return
  5810. else:
  5811. self.export_excellon(name, filename)
  5812. if self.defaults["global_open_style"] is False:
  5813. self.file_opened.emit("Excellon", filename)
  5814. self.file_saved.emit("Excellon", filename)
  5815. def on_file_exportgerber(self):
  5816. """
  5817. Callback for menu item File->Export->Gerber.
  5818. :return: None
  5819. """
  5820. self.report_usage("on_file_exportgerber")
  5821. App.log.debug("on_file_exportgerber()")
  5822. obj = self.collection.get_active()
  5823. if obj is None:
  5824. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Gerber object to export."))
  5825. return
  5826. # Check for more compatible types and add as required
  5827. if not isinstance(obj, FlatCAMGerber):
  5828. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5829. return
  5830. name = self.collection.get_active().options["name"]
  5831. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  5832. try:
  5833. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5834. caption=_("Export Gerber"),
  5835. directory=self.get_last_save_folder() + '/' + name,
  5836. filter=_filter_)
  5837. except TypeError:
  5838. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  5839. filename = str(filename)
  5840. if filename == "":
  5841. self.inform.emit(_("[WARNING_NOTCL] Export Gerber cancelled."))
  5842. return
  5843. else:
  5844. self.export_gerber(name, filename)
  5845. if self.defaults["global_open_style"] is False:
  5846. self.file_opened.emit("Gerber", filename)
  5847. self.file_saved.emit("Gerber", filename)
  5848. def on_file_exportdxf(self):
  5849. """
  5850. Callback for menu item File->Export DXF.
  5851. :return: None
  5852. """
  5853. self.report_usage("on_file_exportdxf")
  5854. App.log.debug("on_file_exportdxf()")
  5855. obj = self.collection.get_active()
  5856. if obj is None:
  5857. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5858. msg = _("Please Select a Geometry object to export")
  5859. msgbox = QtWidgets.QMessageBox()
  5860. msgbox.setInformativeText(msg)
  5861. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5862. msgbox.setDefaultButton(bt_ok)
  5863. msgbox.exec_()
  5864. return
  5865. # Check for more compatible types and add as required
  5866. if not isinstance(obj, FlatCAMGeometry):
  5867. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  5868. msgbox = QtWidgets.QMessageBox()
  5869. msgbox.setInformativeText(msg)
  5870. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5871. msgbox.setDefaultButton(bt_ok)
  5872. msgbox.exec_()
  5873. return
  5874. name = self.collection.get_active().options["name"]
  5875. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5876. try:
  5877. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5878. caption=_("Export DXF"),
  5879. directory=self.get_last_save_folder() + '/' + name,
  5880. filter=_filter_)
  5881. except TypeError:
  5882. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  5883. filter=_filter_)
  5884. filename = str(filename)
  5885. if filename == "":
  5886. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  5887. return
  5888. else:
  5889. self.export_dxf(name, filename)
  5890. if self.defaults["global_open_style"] is False:
  5891. self.file_opened.emit("DXF", filename)
  5892. self.file_saved.emit("DXF", filename)
  5893. def on_file_importsvg(self, type_of_obj):
  5894. """
  5895. Callback for menu item File->Import SVG.
  5896. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5897. :type type_of_obj: str
  5898. :return: None
  5899. """
  5900. self.report_usage("on_file_importsvg")
  5901. App.log.debug("on_file_importsvg()")
  5902. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  5903. try:
  5904. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5905. directory=self.get_last_folder(), filter=_filter_)
  5906. except TypeError:
  5907. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5908. filter=_filter_)
  5909. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5910. type_of_obj = "geometry"
  5911. filenames = [str(filename) for filename in filenames]
  5912. if len(filenames) == 0:
  5913. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  5914. else:
  5915. for filename in filenames:
  5916. if filename != '':
  5917. self.worker_task.emit({'fcn': self.import_svg,
  5918. 'params': [filename, type_of_obj]})
  5919. def on_file_importdxf(self, type_of_obj):
  5920. """
  5921. Callback for menu item File->Import DXF.
  5922. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5923. :type type_of_obj: str
  5924. :return: None
  5925. """
  5926. self.report_usage("on_file_importdxf")
  5927. App.log.debug("on_file_importdxf()")
  5928. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5929. try:
  5930. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5931. directory=self.get_last_folder(),
  5932. filter=_filter_)
  5933. except TypeError:
  5934. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5935. filter=_filter_)
  5936. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5937. type_of_obj = "geometry"
  5938. filenames = [str(filename) for filename in filenames]
  5939. if len(filenames) == 0:
  5940. self.inform.emit(_("[WARNING_NOTCL] Open DXF cancelled."))
  5941. else:
  5942. for filename in filenames:
  5943. if filename != '':
  5944. self.worker_task.emit({'fcn': self.import_dxf,
  5945. 'params': [filename, type_of_obj]})
  5946. # ###############################################################################################################
  5947. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5948. # ###############################################################################################################
  5949. def init_code_editor(self, name):
  5950. # Signals section
  5951. # Disconnect the old signals
  5952. self.ui.buttonOpen.clicked.disconnect()
  5953. self.ui.buttonSave.clicked.disconnect()
  5954. # add the tab if it was closed
  5955. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  5956. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  5957. # delete the absolute and relative position and messages in the infobar
  5958. self.ui.position_label.setText("")
  5959. self.ui.rel_position_label.setText("")
  5960. # first clear previous text in text editor (if any)
  5961. self.ui.code_editor.clear()
  5962. self.ui.code_editor.setReadOnly(False)
  5963. self.toggle_codeeditor = True
  5964. self.ui.code_editor.completer_enable = False
  5965. # Switch plot_area to CNCJob tab
  5966. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5967. def on_view_source(self):
  5968. try:
  5969. obj = self.collection.get_active()
  5970. except:
  5971. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  5972. return 'fail'
  5973. # then append the text from GCode to the text editor
  5974. try:
  5975. file = StringIO(obj.source_file)
  5976. except AttributeError:
  5977. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  5978. return 'fail'
  5979. if obj.kind == 'gerber':
  5980. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  5981. elif obj.kind == 'excellon':
  5982. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  5983. self.init_code_editor(name=_("Source Editor"))
  5984. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5985. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5986. try:
  5987. for line in file:
  5988. proc_line = str(line).strip('\n')
  5989. self.ui.code_editor.append(proc_line)
  5990. except Exception as e:
  5991. log.debug('App.on_view_source() -->%s' % str(e))
  5992. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  5993. return
  5994. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5995. self.handleTextChanged()
  5996. self.ui.show()
  5997. def on_toggle_code_editor(self):
  5998. self.report_usage("on_toggle_code_editor()")
  5999. if self.toggle_codeeditor is False:
  6000. self.init_code_editor(name=_("Code Editor"))
  6001. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  6002. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  6003. else:
  6004. for idx in range(self.ui.plot_tab_area.count()):
  6005. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  6006. self.ui.plot_tab_area.closeTab(idx)
  6007. break
  6008. self.toggle_codeeditor = False
  6009. def on_filenewscript(self):
  6010. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6011. self.init_code_editor(name=_("Script Editor"))
  6012. self.ui.code_editor.completer_enable = True
  6013. self.ui.code_editor.append(_(
  6014. "#\n"
  6015. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  6016. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  6017. "#\n\n"
  6018. "# FlatCAM commands list:\n"
  6019. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  6020. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  6021. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  6022. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  6023. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  6024. "# WriteGCode\n"
  6025. "#\n\n"
  6026. ))
  6027. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6028. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6029. self.handleTextChanged()
  6030. self.ui.code_editor.show()
  6031. def on_fileopenscript(self):
  6032. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6033. try:
  6034. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  6035. directory=self.get_last_folder(), filter=_filter_)
  6036. except TypeError:
  6037. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  6038. # The Qt methods above will return a QString which can cause problems later.
  6039. # So far json.dump() will fail to serialize it.
  6040. # TODO: Improve the serialization methods and remove this fix.
  6041. filename = str(filename)
  6042. if filename == "":
  6043. self.inform.emit(_("[WARNING_NOTCL] Open TCL script cancelled."))
  6044. else:
  6045. self.on_filenewscript()
  6046. try:
  6047. with open(filename, "r") as opened_script:
  6048. try:
  6049. for line in opened_script:
  6050. proc_line = str(line).strip('\n')
  6051. self.ui.code_editor.append(proc_line)
  6052. except Exception as e:
  6053. log.debug('App.on_fileopenscript() -->%s' % str(e))
  6054. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  6055. return
  6056. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6057. self.handleTextChanged()
  6058. self.ui.show()
  6059. except Exception as e:
  6060. log.debug("App.on_fileopenscript() -> %s" % str(e))
  6061. def on_filerunscript(self, name=None):
  6062. """
  6063. File menu callback for loading and running a TCL script.
  6064. :return: None
  6065. """
  6066. self.report_usage("on_filerunscript")
  6067. App.log.debug("on_file_runscript()")
  6068. if name:
  6069. filename = name
  6070. else:
  6071. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6072. try:
  6073. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6074. directory=self.get_last_folder(), filter=_filter_)
  6075. except TypeError:
  6076. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6077. # The Qt methods above will return a QString which can cause problems later.
  6078. # So far json.dump() will fail to serialize it.
  6079. # TODO: Improve the serialization methods and remove this fix.
  6080. filename = str(filename)
  6081. if filename == "":
  6082. self.inform.emit(_("[WARNING_NOTCL] Run TCL script cancelled."))
  6083. else:
  6084. try:
  6085. with open(filename, "r") as tcl_script:
  6086. cmd_line_shellfile_content = tcl_script.read()
  6087. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  6088. except Exception as e:
  6089. log.debug("App.on_filerunscript() -> %s" % str(e))
  6090. sys.exit(2)
  6091. def on_file_saveproject(self):
  6092. """
  6093. Callback for menu item File->Save Project. Saves the project to
  6094. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6095. if set to None. The project is saved by calling ``self.save_project()``.
  6096. :return: None
  6097. """
  6098. self.report_usage("on_file_saveproject")
  6099. if self.project_filename is None:
  6100. self.on_file_saveprojectas()
  6101. else:
  6102. self.worker_task.emit({'fcn': self.save_project,
  6103. 'params': [self.project_filename]})
  6104. if self.defaults["global_open_style"] is False:
  6105. self.file_opened.emit("project", self.project_filename)
  6106. self.file_saved.emit("project", self.project_filename)
  6107. self.set_ui_title(name=self.project_filename)
  6108. self.should_we_save = False
  6109. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6110. """
  6111. Callback for menu item File->Save Project As... Opens a file
  6112. chooser and saves the project to the given file via
  6113. ``self.save_project()``.
  6114. :param make_copy if to be create a copy of the project; boolean
  6115. :param use_thread: if to be run in a separate thread; boolean
  6116. :param quit_action: if to be followed by quiting the application; boolean
  6117. :return: None
  6118. """
  6119. self.report_usage("on_file_saveprojectas")
  6120. self.date = str(datetime.today()).rpartition('.')[0]
  6121. self.date = ''.join(c for c in self.date if c not in ':-')
  6122. self.date = self.date.replace(' ', '_')
  6123. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  6124. try:
  6125. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6126. caption=_("Save Project As ..."),
  6127. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  6128. filter=filter_)
  6129. except TypeError:
  6130. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  6131. filename = str(filename)
  6132. if filename == '':
  6133. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  6134. return
  6135. try:
  6136. f = open(filename, 'r')
  6137. f.close()
  6138. except IOError:
  6139. pass
  6140. if use_thread is True:
  6141. self.worker_task.emit({'fcn': self.save_project,
  6142. 'params': [filename, quit_action]})
  6143. else:
  6144. self.save_project(filename, quit_action)
  6145. # self.save_project(filename)
  6146. if self.defaults["global_open_style"] is False:
  6147. self.file_opened.emit("project", filename)
  6148. self.file_saved.emit("project", filename)
  6149. if not make_copy:
  6150. self.project_filename = filename
  6151. self.set_ui_title(name=self.project_filename)
  6152. self.should_we_save = False
  6153. def export_svg(self, obj_name, filename, scale_factor=0.00):
  6154. """
  6155. Exports a Geometry Object to an SVG file.
  6156. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6157. :param filename: Path to the SVG file to save to.
  6158. :param scale_factor: factor by which to change/scale the thickness of the features
  6159. :return:
  6160. """
  6161. self.report_usage("export_svg()")
  6162. if filename is None:
  6163. filename = self.defaults["global_last_save_folder"]
  6164. self.log.debug("export_svg()")
  6165. try:
  6166. obj = self.collection.get_by_name(str(obj_name))
  6167. except:
  6168. # TODO: The return behavior has not been established... should raise exception?
  6169. return "Could not retrieve object: %s" % obj_name
  6170. with self.proc_container.new(_("Exporting SVG")) as proc:
  6171. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6172. # Determine bounding area for svg export
  6173. bounds = obj.bounds()
  6174. size = obj.size()
  6175. # Convert everything to strings for use in the xml doc
  6176. svgwidth = str(size[0])
  6177. svgheight = str(size[1])
  6178. minx = str(bounds[0])
  6179. miny = str(bounds[1] - size[1])
  6180. uom = obj.units.lower()
  6181. # Add a SVG Header and footer to the svg output from shapely
  6182. # The transform flips the Y Axis so that everything renders
  6183. # properly within svg apps such as inkscape
  6184. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6185. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6186. svg_header += 'width="' + svgwidth + uom + '" '
  6187. svg_header += 'height="' + svgheight + uom + '" '
  6188. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6189. svg_header += '<g transform="scale(1,-1)">'
  6190. svg_footer = '</g> </svg>'
  6191. svg_elem = svg_header + exported_svg + svg_footer
  6192. # Parse the xml through a xml parser just to add line feeds
  6193. # and to make it look more pretty for the output
  6194. svgcode = parse_xml_string(svg_elem)
  6195. try:
  6196. with open(filename, 'w') as fp:
  6197. fp.write(svgcode.toprettyxml())
  6198. except PermissionError:
  6199. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6200. "Most likely another app is holding the file open and not accessible."))
  6201. return 'fail'
  6202. if self.defaults["global_open_style"] is False:
  6203. self.file_opened.emit("SVG", filename)
  6204. self.file_saved.emit("SVG", filename)
  6205. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  6206. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  6207. """
  6208. Exports a Geometry Object to an SVG file in negative.
  6209. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6210. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6211. :param filename: Path to the SVG file to save to.
  6212. :param boundary: thickness of a black border to surround all the features
  6213. :param scale_factor: factor by which to change/scale the thickness of the features
  6214. :param use_thread: if to be run in a separate thread; boolean
  6215. :return:
  6216. """
  6217. self.report_usage("export_negative()")
  6218. if filename is None:
  6219. filename = self.defaults["global_last_save_folder"]
  6220. self.log.debug("export_svg() negative")
  6221. try:
  6222. obj = self.collection.get_by_name(str(obj_name))
  6223. except:
  6224. # TODO: The return behavior has not been established... should raise exception?
  6225. return "Could not retrieve object: %s" % obj_name
  6226. try:
  6227. box = self.collection.get_by_name(str(box_name))
  6228. except:
  6229. # TODO: The return behavior has not been established... should raise exception?
  6230. return "Could not retrieve object: %s" % box_name
  6231. if box is None:
  6232. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  6233. box = obj
  6234. def make_negative_film():
  6235. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6236. self.progress.emit(40)
  6237. # Determine bounding area for svg export
  6238. bounds = box.bounds()
  6239. size = box.size()
  6240. uom = obj.units.lower()
  6241. # Convert everything to strings for use in the xml doc
  6242. svgwidth = str(size[0] + (2 * boundary))
  6243. svgheight = str(size[1] + (2 * boundary))
  6244. minx = str(bounds[0] - boundary)
  6245. miny = str(bounds[1] + boundary + size[1])
  6246. miny_rect = str(bounds[1] - boundary)
  6247. # Add a SVG Header and footer to the svg output from shapely
  6248. # The transform flips the Y Axis so that everything renders
  6249. # properly within svg apps such as inkscape
  6250. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6251. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6252. svg_header += 'width="' + svgwidth + uom + '" '
  6253. svg_header += 'height="' + svgheight + uom + '" '
  6254. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6255. svg_header += '>'
  6256. svg_header += '<g transform="scale(1,-1)">'
  6257. svg_footer = '</g> </svg>'
  6258. self.progress.emit(60)
  6259. # Change the attributes of the exported SVG
  6260. # We don't need stroke-width - wrong, we do when we have lines with certain width
  6261. # We set opacity to maximum
  6262. # We set the color to WHITE
  6263. root = ET.fromstring(exported_svg)
  6264. for child in root:
  6265. child.set('fill', '#FFFFFF')
  6266. child.set('opacity', '1.0')
  6267. child.set('stroke', '#FFFFFF')
  6268. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  6269. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  6270. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  6271. first_svg_elem_tag = 'rect'
  6272. first_svg_elem_attribs = {
  6273. 'x': minx,
  6274. 'y': miny_rect,
  6275. 'width': svgwidth,
  6276. 'height': svgheight,
  6277. 'id': 'neg_rect',
  6278. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  6279. }
  6280. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  6281. exported_svg = ET.tostring(root)
  6282. svg_elem = svg_header + str(exported_svg) + svg_footer
  6283. self.progress.emit(80)
  6284. # Parse the xml through a xml parser just to add line feeds
  6285. # and to make it look more pretty for the output
  6286. doc = parse_xml_string(svg_elem)
  6287. try:
  6288. with open(filename, 'w') as fp:
  6289. fp.write(doc.toprettyxml())
  6290. except PermissionError:
  6291. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6292. "Most likely another app is holding the file open and not accessible."))
  6293. return 'fail'
  6294. self.progress.emit(100)
  6295. if self.defaults["global_open_style"] is False:
  6296. self.file_opened.emit("SVG", filename)
  6297. self.file_saved.emit("SVG", filename)
  6298. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  6299. if use_thread is True:
  6300. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  6301. def job_thread_film(app_obj):
  6302. try:
  6303. make_negative_film()
  6304. except Exception as e:
  6305. proc.done()
  6306. return
  6307. proc.done()
  6308. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  6309. else:
  6310. make_negative_film()
  6311. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  6312. """
  6313. Exports a Geometry Object to an SVG file in positive black.
  6314. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6315. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6316. :param filename: Path to the SVG file to save to.
  6317. :param scale_factor: factor by which to change/scale the thickness of the features
  6318. :param use_thread: if to be run in a separate thread; boolean
  6319. :return:
  6320. """
  6321. self.report_usage("export_svg_black()")
  6322. if filename is None:
  6323. filename = self.defaults["global_last_save_folder"]
  6324. self.log.debug("export_svg() black")
  6325. try:
  6326. obj = self.collection.get_by_name(str(obj_name))
  6327. except:
  6328. # TODO: The return behavior has not been established... should raise exception?
  6329. return "Could not retrieve object: %s" % obj_name
  6330. try:
  6331. box = self.collection.get_by_name(str(box_name))
  6332. except:
  6333. # TODO: The return behavior has not been established... should raise exception?
  6334. return "Could not retrieve object: %s" % box_name
  6335. if box is None:
  6336. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  6337. box = obj
  6338. def make_black_film():
  6339. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6340. self.progress.emit(40)
  6341. # Change the attributes of the exported SVG
  6342. # We don't need stroke-width
  6343. # We set opacity to maximum
  6344. # We set the colour to WHITE
  6345. root = ET.fromstring(exported_svg)
  6346. for child in root:
  6347. child.set('fill', '#000000')
  6348. child.set('opacity', '1.0')
  6349. child.set('stroke', '#000000')
  6350. exported_svg = ET.tostring(root)
  6351. # Determine bounding area for svg export
  6352. bounds = box.bounds()
  6353. size = box.size()
  6354. # This contain the measure units
  6355. uom = obj.units.lower()
  6356. # Define a boundary around SVG of about 1.0mm (~39mils)
  6357. if uom in "mm":
  6358. boundary = 1.0
  6359. else:
  6360. boundary = 0.0393701
  6361. self.progress.emit(80)
  6362. # Convert everything to strings for use in the xml doc
  6363. svgwidth = str(size[0] + (2 * boundary))
  6364. svgheight = str(size[1] + (2 * boundary))
  6365. minx = str(bounds[0] - boundary)
  6366. miny = str(bounds[1] + boundary + size[1])
  6367. self.log.debug(minx)
  6368. self.log.debug(miny)
  6369. # Add a SVG Header and footer to the svg output from shapely
  6370. # The transform flips the Y Axis so that everything renders
  6371. # properly within svg apps such as inkscape
  6372. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6373. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6374. svg_header += 'width="' + svgwidth + uom + '" '
  6375. svg_header += 'height="' + svgheight + uom + '" '
  6376. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6377. svg_header += '>'
  6378. svg_header += '<g transform="scale(1,-1)">'
  6379. svg_footer = '</g> </svg>'
  6380. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  6381. self.progress.emit(90)
  6382. # Parse the xml through a xml parser just to add line feeds
  6383. # and to make it look more pretty for the output
  6384. doc = parse_xml_string(svg_elem)
  6385. try:
  6386. with open(filename, 'w') as fp:
  6387. fp.write(doc.toprettyxml())
  6388. except PermissionError:
  6389. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6390. "Most likely another app is holding the file open and not accessible."))
  6391. return 'fail'
  6392. self.progress.emit(100)
  6393. if self.defaults["global_open_style"] is False:
  6394. self.file_opened.emit("SVG", filename)
  6395. self.file_saved.emit("SVG", filename)
  6396. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  6397. if use_thread is True:
  6398. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  6399. def job_thread_film(app_obj):
  6400. try:
  6401. make_black_film()
  6402. except Exception as e:
  6403. proc.done()
  6404. return
  6405. proc.done()
  6406. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  6407. else:
  6408. make_black_film()
  6409. def save_source_file(self, obj_name, filename, use_thread=True):
  6410. """
  6411. Exports a FlatCAM Object to an Gerber/Excellon file.
  6412. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6413. :param filename: Path to the Gerber file to save to.
  6414. :param use_thread: if to be run in a separate thread
  6415. :return:
  6416. """
  6417. self.report_usage("save source file()")
  6418. if filename is None:
  6419. filename = self.defaults["global_last_save_folder"]
  6420. self.log.debug("save source file()")
  6421. obj = self.collection.get_by_name(obj_name)
  6422. file_string = StringIO(obj.source_file)
  6423. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6424. try:
  6425. with open(filename, 'w') as file:
  6426. file.writelines('G04*\n')
  6427. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6428. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6429. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6430. file.writelines('G04 Created on : %s*\n' % time_string)
  6431. for line in file_string:
  6432. file.writelines(line)
  6433. except PermissionError:
  6434. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6435. "Most likely another app is holding the file open and not accessible."))
  6436. return 'fail'
  6437. def export_excellon(self, obj_name, filename, use_thread=True):
  6438. """
  6439. Exports a Excellon Object to an Excellon file.
  6440. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6441. :param filename: Path to the Excellon file to save to.
  6442. :param use_thread: if to be run in a separate thread
  6443. :return:
  6444. """
  6445. self.report_usage("export_excellon()")
  6446. if filename is None:
  6447. filename = self.defaults["global_last_save_folder"]
  6448. self.log.debug("export_excellon()")
  6449. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6450. self.defaults["excellon_exp_decimals"]
  6451. )
  6452. units = ''
  6453. try:
  6454. obj = self.collection.get_by_name(str(obj_name))
  6455. except:
  6456. # TODO: The return behavior has not been established... should raise exception?
  6457. return "Could not retrieve object: %s" % obj_name
  6458. # updated units
  6459. eunits = self.defaults["excellon_exp_units"]
  6460. ewhole = self.defaults["excellon_exp_integer"]
  6461. efract = self.defaults["excellon_exp_decimals"]
  6462. ezeros = self.defaults["excellon_exp_zeros"]
  6463. eformat = self.defaults["excellon_exp_format"]
  6464. slot_type = self.defaults["excellon_exp_slot_type"]
  6465. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6466. if fc_units == 'MM':
  6467. factor = 1 if eunits == 'METRIC' else 0.03937
  6468. else:
  6469. factor = 25.4 if eunits == 'METRIC' else 1
  6470. def make_excellon():
  6471. try:
  6472. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6473. header = 'M48\n'
  6474. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6475. (str(self.version), str(self.version_date))
  6476. header += ';Filename: %s' % str(obj_name) + '\n'
  6477. header += ';Created on : %s' % time_str + '\n'
  6478. if eformat == 'dec':
  6479. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6480. header += eunits + '\n'
  6481. for tool in obj.tools:
  6482. if eunits == 'METRIC':
  6483. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6484. tool=str(tool),
  6485. dec=2)
  6486. else:
  6487. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6488. tool=str(tool),
  6489. dec=4)
  6490. else:
  6491. if ezeros == 'LZ':
  6492. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6493. form='ndec', e_zeros='LZ', factor=factor,
  6494. slot_type=slot_type)
  6495. header += '%s,%s\n' % (eunits, 'LZ')
  6496. header += format_exc
  6497. for tool in obj.tools:
  6498. if eunits == 'METRIC':
  6499. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6500. tool=str(tool),
  6501. dec=2)
  6502. else:
  6503. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6504. tool=str(tool),
  6505. dec=4)
  6506. else:
  6507. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6508. form='ndec', e_zeros='TZ', factor=factor,
  6509. slot_type=slot_type)
  6510. header += '%s,%s\n' % (eunits, 'TZ')
  6511. header += format_exc
  6512. for tool in obj.tools:
  6513. if eunits == 'METRIC':
  6514. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6515. tool=str(tool),
  6516. dec=2)
  6517. else:
  6518. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6519. tool=str(tool),
  6520. dec=4)
  6521. header += '%\n'
  6522. footer = 'M30\n'
  6523. exported_excellon = header
  6524. exported_excellon += excellon_code
  6525. exported_excellon += footer
  6526. try:
  6527. with open(filename, 'w') as fp:
  6528. fp.write(exported_excellon)
  6529. except PermissionError:
  6530. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6531. "Most likely another app is holding the file open and not accessible."))
  6532. return 'fail'
  6533. if self.defaults["global_open_style"] is False:
  6534. self.file_opened.emit("Excellon", filename)
  6535. self.file_saved.emit("Excellon", filename)
  6536. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  6537. except Exception as e:
  6538. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6539. return 'fail'
  6540. if use_thread is True:
  6541. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6542. def job_thread_exc(app_obj):
  6543. ret = make_excellon()
  6544. if ret == 'fail':
  6545. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  6546. return
  6547. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6548. else:
  6549. ret = make_excellon()
  6550. if ret == 'fail':
  6551. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  6552. return
  6553. def export_gerber(self, obj_name, filename, use_thread=True):
  6554. """
  6555. Exports a Gerber Object to an Gerber file.
  6556. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6557. :param filename: Path to the Gerber file to save to.
  6558. :param use_thread: if to be run in a separate thread
  6559. :return:
  6560. """
  6561. self.report_usage("export_gerber()")
  6562. if filename is None:
  6563. filename = self.defaults["global_last_save_folder"]
  6564. self.log.debug("export_gerber()")
  6565. try:
  6566. obj = self.collection.get_by_name(str(obj_name))
  6567. except:
  6568. # TODO: The return behavior has not been established... should raise exception?
  6569. return "Could not retrieve object: %s" % obj_name
  6570. # updated units
  6571. gunits = self.defaults["gerber_exp_units"]
  6572. gwhole = self.defaults["gerber_exp_integer"]
  6573. gfract = self.defaults["gerber_exp_decimals"]
  6574. gzeros = self.defaults["gerber_exp_zeros"]
  6575. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6576. if fc_units == 'MM':
  6577. factor = 1 if gunits == 'MM' else 0.03937
  6578. else:
  6579. factor = 25.4 if gunits == 'MM' else 1
  6580. def make_gerber():
  6581. try:
  6582. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6583. header = 'G04*\n'
  6584. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6585. (str(self.version), str(self.version_date))
  6586. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6587. header += 'G04 Created on : %s*' % time_str + '\n'
  6588. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6589. header += "%MO{units}*%\n".format(units=gunits)
  6590. for apid in obj.apertures:
  6591. if obj.apertures[apid]['type'] == 'C':
  6592. header += "%ADD{apid}{type},{size}*%\n".format(
  6593. apid=str(apid),
  6594. type='C',
  6595. size=(factor * obj.apertures[apid]['size'])
  6596. )
  6597. elif obj.apertures[apid]['type'] == 'R':
  6598. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6599. apid=str(apid),
  6600. type='R',
  6601. width=(factor * obj.apertures[apid]['width']),
  6602. height=(factor * obj.apertures[apid]['height'])
  6603. )
  6604. elif obj.apertures[apid]['type'] == 'O':
  6605. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6606. apid=str(apid),
  6607. type='O',
  6608. width=(factor * obj.apertures[apid]['width']),
  6609. height=(factor * obj.apertures[apid]['height'])
  6610. )
  6611. header += '\n'
  6612. # obsolete units but some software may need it
  6613. if gunits == 'IN':
  6614. header += 'G70*\n'
  6615. else:
  6616. header += 'G71*\n'
  6617. # Absolute Mode
  6618. header += 'G90*\n'
  6619. header += 'G01*\n'
  6620. # positive polarity
  6621. header += '%LPD*%\n'
  6622. footer = 'M02*\n'
  6623. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6624. exported_gerber = header
  6625. exported_gerber += gerber_code
  6626. exported_gerber += footer
  6627. try:
  6628. with open(filename, 'w') as fp:
  6629. fp.write(exported_gerber)
  6630. except PermissionError:
  6631. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6632. "Most likely another app is holding the file open and not accessible."))
  6633. return 'fail'
  6634. if self.defaults["global_open_style"] is False:
  6635. self.file_opened.emit("Gerber", filename)
  6636. self.file_saved.emit("Gerber", filename)
  6637. self.inform.emit(_("[success] Gerber file exported to %s") % filename)
  6638. except Exception as e:
  6639. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6640. return 'fail'
  6641. if use_thread is True:
  6642. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6643. def job_thread_exc(app_obj):
  6644. ret = make_gerber()
  6645. if ret == 'fail':
  6646. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  6647. return
  6648. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6649. else:
  6650. ret = make_gerber()
  6651. if ret == 'fail':
  6652. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  6653. return
  6654. def export_dxf(self, obj_name, filename, use_thread=True):
  6655. """
  6656. Exports a Geometry Object to an DXF file.
  6657. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6658. :param filename: Path to the DXF file to save to.
  6659. :param use_thread: if to be run in a separate thread
  6660. :return:
  6661. """
  6662. self.report_usage("export_dxf()")
  6663. if filename is None:
  6664. filename = self.defaults["global_last_save_folder"]
  6665. self.log.debug("export_dxf()")
  6666. format_exc = ''
  6667. units = ''
  6668. try:
  6669. obj = self.collection.get_by_name(str(obj_name))
  6670. except:
  6671. # TODO: The return behavior has not been established... should raise exception?
  6672. return "Could not retrieve object: %s" % obj_name
  6673. # updated units
  6674. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6675. if units == 'IN' or units == 'INCH':
  6676. units = 'INCH'
  6677. elif units == 'MM' or units == 'METIRC':
  6678. units ='METRIC'
  6679. def make_dxf():
  6680. try:
  6681. dxf_code = obj.export_dxf()
  6682. dxf_code.saveas(filename)
  6683. if self.defaults["global_open_style"] is False:
  6684. self.file_opened.emit("DXF", filename)
  6685. self.file_saved.emit("DXF", filename)
  6686. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  6687. except:
  6688. return 'fail'
  6689. if use_thread is True:
  6690. with self.proc_container.new(_("Exporting DXF")) as proc:
  6691. def job_thread_exc(app_obj):
  6692. ret = make_dxf()
  6693. if ret == 'fail':
  6694. app_obj.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6695. return
  6696. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6697. else:
  6698. ret = make_dxf()
  6699. if ret == 'fail':
  6700. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6701. return
  6702. def import_svg(self, filename, geo_type='geometry', outname=None):
  6703. """
  6704. Adds a new Geometry Object to the projects and populates
  6705. it with shapes extracted from the SVG file.
  6706. :param filename: Path to the SVG file.
  6707. :param outname:
  6708. :return:
  6709. """
  6710. self.report_usage("import_svg()")
  6711. obj_type = ""
  6712. if geo_type is None or geo_type == "geometry":
  6713. obj_type = "geometry"
  6714. elif geo_type == "gerber":
  6715. obj_type = geo_type
  6716. else:
  6717. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6718. "Only Geometry and Gerber are supported"))
  6719. return
  6720. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6721. def obj_init(geo_obj, app_obj):
  6722. geo_obj.import_svg(filename, obj_type, units=units)
  6723. geo_obj.multigeo = False
  6724. with self.proc_container.new(_("Importing SVG")) as proc:
  6725. # Object name
  6726. name = outname or filename.split('/')[-1].split('\\')[-1]
  6727. self.new_object(obj_type, name, obj_init, autoselected=False)
  6728. self.progress.emit(20)
  6729. # Register recent file
  6730. self.file_opened.emit("svg", filename)
  6731. # GUI feedback
  6732. self.inform.emit(_("[success] Opened: %s") % filename)
  6733. self.progress.emit(100)
  6734. def import_dxf(self, filename, geo_type='geometry', outname=None):
  6735. """
  6736. Adds a new Geometry Object to the projects and populates
  6737. it with shapes extracted from the DXF file.
  6738. :param filename: Path to the DXF file.
  6739. :param outname:
  6740. :type putname: str
  6741. :return:
  6742. """
  6743. self.report_usage("import_dxf()")
  6744. obj_type = ""
  6745. if geo_type is None or geo_type == "geometry":
  6746. obj_type = "geometry"
  6747. elif geo_type == "gerber":
  6748. obj_type = geo_type
  6749. else:
  6750. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6751. "Only Geometry and Gerber are supported"))
  6752. return
  6753. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6754. def obj_init(geo_obj, app_obj):
  6755. geo_obj.import_dxf(filename, obj_type, units=units)
  6756. geo_obj.multigeo = False
  6757. with self.proc_container.new(_("Importing DXF")) as proc:
  6758. # Object name
  6759. name = outname or filename.split('/')[-1].split('\\')[-1]
  6760. self.new_object(obj_type, name, obj_init, autoselected=False)
  6761. self.progress.emit(20)
  6762. # Register recent file
  6763. self.file_opened.emit("dxf", filename)
  6764. # GUI feedback
  6765. self.inform.emit(_("[success] Opened: %s") % filename)
  6766. self.progress.emit(100)
  6767. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  6768. """
  6769. Adds a new Geometry Object to the projects and populates
  6770. it with shapes extracted from the SVG file.
  6771. :param filename: Path to the SVG file.
  6772. :param o_type: type of FlatCAM objeect
  6773. :param dpi: dot per inch
  6774. :param mode: black or color
  6775. :param mask: dictate the level of detail
  6776. :param outname: name for the resulting file
  6777. :return:
  6778. """
  6779. self.report_usage("import_image()")
  6780. if o_type is None or o_type == "geometry":
  6781. obj_type = "geometry"
  6782. elif o_type == "gerber":
  6783. obj_type = o_type
  6784. else:
  6785. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6786. "Only Geometry and Gerber are supported"))
  6787. return
  6788. def obj_init(geo_obj, app_obj):
  6789. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  6790. geo_obj.multigeo = False
  6791. with self.proc_container.new(_("Importing Image")) as proc:
  6792. # Object name
  6793. name = outname or filename.split('/')[-1].split('\\')[-1]
  6794. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  6795. self.new_object(obj_type, name, obj_init)
  6796. self.progress.emit(20)
  6797. # Register recent file
  6798. self.file_opened.emit("image", filename)
  6799. # GUI feedback
  6800. self.inform.emit(_("[success] Opened: %s") % filename)
  6801. self.progress.emit(100)
  6802. def open_gerber(self, filename, outname=None):
  6803. """
  6804. Opens a Gerber file, parses it and creates a new object for
  6805. it in the program. Thread-safe.
  6806. :param outname: Name of the resulting object. None causes the
  6807. name to be that of the file.
  6808. :param filename: Gerber file filename
  6809. :type filename: str
  6810. :param follow: If true, the parser will not create polygons, just lines
  6811. following the gerber path.
  6812. :type follow: bool
  6813. :return: None
  6814. """
  6815. # How the object should be initialized
  6816. def obj_init(gerber_obj, app_obj):
  6817. assert isinstance(gerber_obj, FlatCAMGerber), \
  6818. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  6819. # Opening the file happens here
  6820. self.progress.emit(30)
  6821. try:
  6822. gerber_obj.parse_file(filename)
  6823. except IOError:
  6824. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  6825. app_obj.progress.emit(0)
  6826. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  6827. return "fail"
  6828. except ParseError as err:
  6829. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename,
  6830. error=str(err)))
  6831. app_obj.progress.emit(0)
  6832. self.log.error(str(err))
  6833. return "fail"
  6834. except Exception as e:
  6835. log.debug("App.open_gerber() --> %s" % str(e))
  6836. msg = _("[ERROR] An internal error has occurred. See shell.\n")
  6837. msg += traceback.format_exc()
  6838. app_obj.inform.emit(msg)
  6839. return "fail"
  6840. if gerber_obj.is_empty():
  6841. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  6842. # self.collection.set_active(gerber_obj.options["name"])
  6843. # self.collection.delete_active()
  6844. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  6845. return "fail"
  6846. # Further parsing
  6847. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  6848. App.log.debug("open_gerber()")
  6849. with self.proc_container.new(_("Opening Gerber")) as proc:
  6850. self.progress.emit(10)
  6851. # Object name
  6852. name = outname or filename.split('/')[-1].split('\\')[-1]
  6853. # # ## Object creation # ##
  6854. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  6855. if ret == 'fail':
  6856. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  6857. return
  6858. # Register recent file
  6859. self.file_opened.emit("gerber", filename)
  6860. self.progress.emit(100)
  6861. # GUI feedback
  6862. self.inform.emit(_("[success] Opened: %s") % filename)
  6863. def open_excellon(self, filename, outname=None):
  6864. """
  6865. Opens an Excellon file, parses it and creates a new object for
  6866. it in the program. Thread-safe.
  6867. :param outname: Name of the resulting object. None causes the
  6868. name to be that of the file.
  6869. :param filename: Excellon file filename
  6870. :type filename: str
  6871. :return: None
  6872. """
  6873. App.log.debug("open_excellon()")
  6874. # How the object should be initialized
  6875. def obj_init(excellon_obj, app_obj):
  6876. # self.progress.emit(20)
  6877. try:
  6878. ret = excellon_obj.parse_file(filename=filename)
  6879. if ret == "fail":
  6880. log.debug("Excellon parsing failed.")
  6881. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  6882. return "fail"
  6883. except IOError:
  6884. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  6885. log.debug("Could not open Excellon object.")
  6886. self.progress.emit(0) # TODO: self and app_bjj mixed
  6887. return "fail"
  6888. except:
  6889. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  6890. msg += traceback.format_exc()
  6891. app_obj.inform.emit(msg)
  6892. return "fail"
  6893. ret = excellon_obj.create_geometry()
  6894. if ret == 'fail':
  6895. log.debug("Could not create geometry for Excellon object.")
  6896. return "fail"
  6897. for tool in excellon_obj.tools:
  6898. if excellon_obj.tools[tool]['solid_geometry']:
  6899. return
  6900. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  6901. return "fail"
  6902. with self.proc_container.new(_("Opening Excellon.")):
  6903. # Object name
  6904. name = outname or filename.split('/')[-1].split('\\')[-1]
  6905. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  6906. if ret_val == 'fail':
  6907. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  6908. return
  6909. # Register recent file
  6910. self.file_opened.emit("excellon", filename)
  6911. # GUI feedback
  6912. self.inform.emit(_("[success] Opened: %s") % filename)
  6913. def open_gcode(self, filename, outname=None):
  6914. """
  6915. Opens a G-gcode file, parses it and creates a new object for
  6916. it in the program. Thread-safe.
  6917. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6918. :param filename: G-code file filename
  6919. :type filename: str
  6920. :return: None
  6921. """
  6922. App.log.debug("open_gcode()")
  6923. # How the object should be initialized
  6924. def obj_init(job_obj, app_obj_):
  6925. """
  6926. :param job_obj: the resulting object
  6927. :type app_obj_: App
  6928. """
  6929. assert isinstance(app_obj_, App), \
  6930. "Initializer expected App, got %s" % type(app_obj_)
  6931. self.progress.emit(10)
  6932. try:
  6933. f = open(filename)
  6934. gcode = f.read()
  6935. f.close()
  6936. except IOError:
  6937. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  6938. self.progress.emit(0)
  6939. return "fail"
  6940. job_obj.gcode = gcode
  6941. self.progress.emit(20)
  6942. ret = job_obj.gcode_parse()
  6943. if ret == "fail":
  6944. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  6945. return "fail"
  6946. self.progress.emit(60)
  6947. job_obj.create_geometry()
  6948. with self.proc_container.new(_("Opening G-Code.")):
  6949. # Object name
  6950. name = outname or filename.split('/')[-1].split('\\')[-1]
  6951. # New object creation and file processing
  6952. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  6953. if ret == 'fail':
  6954. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  6955. "Attempting to create a FlatCAM CNCJob Object from "
  6956. "G-Code file failed during processing"))
  6957. return "fail"
  6958. # Register recent file
  6959. self.file_opened.emit("cncjob", filename)
  6960. # GUI feedback
  6961. self.inform.emit(_("[success] Opened: %s") % filename)
  6962. self.progress.emit(100)
  6963. def open_config_file(self, filename, run_from_arg=None):
  6964. """
  6965. Loads a config file from the specified file.
  6966. :param filename: Name of the file from which to load.
  6967. :type filename: str
  6968. :return: None
  6969. """
  6970. App.log.debug("Opening config file: " + filename)
  6971. # add the tab if it was closed
  6972. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  6973. # first clear previous text in text editor (if any)
  6974. self.ui.code_editor.clear()
  6975. # Switch plot_area to CNCJob tab
  6976. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6977. try:
  6978. if filename:
  6979. f = QtCore.QFile(filename)
  6980. if f.open(QtCore.QIODevice.ReadOnly):
  6981. stream = QtCore.QTextStream(f)
  6982. gcode_edited = stream.readAll()
  6983. self.ui.code_editor.setPlainText(gcode_edited)
  6984. f.close()
  6985. except IOError:
  6986. App.log.error("Failed to open config file: %s" % filename)
  6987. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  6988. return
  6989. def open_project(self, filename, run_from_arg=None):
  6990. """
  6991. Loads a project from the specified file.
  6992. 1) Loads and parses file
  6993. 2) Registers the file as recently opened.
  6994. 3) Calls on_file_new()
  6995. 4) Updates options
  6996. 5) Calls new_object() with the object's from_dict() as init method.
  6997. 6) Calls plot_all()
  6998. :param filename: Name of the file from which to load.
  6999. :type filename: str
  7000. :param run_from_arg: True if run for arguments
  7001. :return: None
  7002. """
  7003. App.log.debug("Opening project: " + filename)
  7004. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7005. # Open and parse an uncompressed Project file
  7006. try:
  7007. f = open(filename, 'r')
  7008. except IOError:
  7009. App.log.error("Failed to open project file: %s" % filename)
  7010. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  7011. return
  7012. try:
  7013. d = json.load(f, object_hook=dict2obj)
  7014. except Exception as e:
  7015. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7016. (filename, str(e)))
  7017. f.close()
  7018. # Open and parse a compressed Project file
  7019. try:
  7020. with lzma.open(filename) as f:
  7021. file_content = f.read().decode('utf-8')
  7022. d = json.loads(file_content, object_hook=dict2obj)
  7023. except Exception as e:
  7024. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7025. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  7026. return
  7027. # Clear the current project
  7028. # # NOT THREAD SAFE # ##
  7029. if run_from_arg is True:
  7030. pass
  7031. else:
  7032. self.on_file_new()
  7033. # Project options
  7034. self.options.update(d['options'])
  7035. self.project_filename = filename
  7036. self.set_screen_units(self.options["units"])
  7037. # Re create objects
  7038. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7039. for obj in d['objs']:
  7040. def obj_init(obj_inst, app_inst):
  7041. obj_inst.from_dict(obj)
  7042. App.log.debug("Recreating from opened project an %s object: %s" %
  7043. (obj['kind'].capitalize(), obj['options']['name']))
  7044. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  7045. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  7046. # self.plot_all()
  7047. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  7048. self.should_we_save = False
  7049. self.file_opened.emit("project", filename)
  7050. self.set_ui_title(name=self.project_filename)
  7051. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7052. def propagate_defaults(self, silent=False):
  7053. """
  7054. This method is used to set default values in classes. It's
  7055. an alternative to project options but allows the use
  7056. of values invisible to the user.
  7057. :return: None
  7058. """
  7059. if silent is False:
  7060. self.log.debug("propagate_defaults()")
  7061. # Which objects to update the given parameters.
  7062. routes = {
  7063. "global_zdownrate": CNCjob,
  7064. "excellon_zeros": Excellon,
  7065. "excellon_format_upper_in": Excellon,
  7066. "excellon_format_lower_in": Excellon,
  7067. "excellon_format_upper_mm": Excellon,
  7068. "excellon_format_lower_mm": Excellon,
  7069. "excellon_units": Excellon,
  7070. "gerber_use_buffer_for_union": Gerber,
  7071. "geometry_multidepth": Geometry
  7072. }
  7073. for param in routes:
  7074. if param in routes[param].defaults:
  7075. try:
  7076. routes[param].defaults[param] = self.defaults[param]
  7077. if silent is False:
  7078. self.log.debug(" " + param + " OK")
  7079. except KeyError:
  7080. if silent is False:
  7081. self.log.debug(" ERROR: " + param + " not in defaults.")
  7082. else:
  7083. # Try extracting the name:
  7084. # classname_param here is param in the object
  7085. if param.find(routes[param].__name__.lower() + "_") == 0:
  7086. p = param[len(routes[param].__name__) + 1:]
  7087. if p in routes[param].defaults:
  7088. routes[param].defaults[p] = self.defaults[param]
  7089. if silent is False:
  7090. self.log.debug(" " + param + " OK!")
  7091. def restore_main_win_geom(self):
  7092. try:
  7093. self.ui.setGeometry(self.defaults["global_def_win_x"],
  7094. self.defaults["global_def_win_y"],
  7095. self.defaults["global_def_win_w"],
  7096. self.defaults["global_def_win_h"])
  7097. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  7098. settings = QSettings("Open Source", "FlatCAM")
  7099. if settings.contains("maximized_gui"):
  7100. maximized_ui = settings.value('maximized_gui', type=bool)
  7101. if maximized_ui is True:
  7102. self.ui.showMaximized()
  7103. except KeyError as e:
  7104. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  7105. def plot_all(self, zoom=True):
  7106. """
  7107. Re-generates all plots from all objects.
  7108. :return: None
  7109. """
  7110. self.log.debug("Plot_all()")
  7111. for obj in self.collection.get_list():
  7112. def worker_task(obj):
  7113. with self.proc_container.new("Plotting"):
  7114. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7115. if zoom:
  7116. self.object_plotted.emit(obj)
  7117. # Send to worker
  7118. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  7119. def register_folder(self, filename):
  7120. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7121. def register_save_folder(self, filename):
  7122. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7123. def set_progress_bar(self, percentage, text=""):
  7124. self.ui.progress_bar.setValue(int(percentage))
  7125. def setup_shell(self):
  7126. """
  7127. Creates shell functions. Runs once at startup.
  7128. :return: None
  7129. """
  7130. self.log.debug("setup_shell()")
  7131. def shelp(p=None):
  7132. if not p:
  7133. return _("Available commands:\n") + \
  7134. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  7135. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  7136. if p not in commands:
  7137. return "Unknown command: %s" % p
  7138. return commands[p]["help"]
  7139. # --- Migrated to new architecture ---
  7140. # def options(name):
  7141. # ops = self.collection.get_by_name(str(name)).options
  7142. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  7143. def h(*args):
  7144. """
  7145. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  7146. and standalone parameters into list.
  7147. """
  7148. kwa = {}
  7149. a = []
  7150. n = len(args)
  7151. name = None
  7152. for i in range(n):
  7153. match = re.search(r'^-([a-zA-Z].*)', args[i])
  7154. if match:
  7155. assert name is None
  7156. name = match.group(1)
  7157. continue
  7158. if name is None:
  7159. a.append(args[i])
  7160. else:
  7161. kwa[name] = args[i]
  7162. name = None
  7163. return a, kwa
  7164. @contextmanager
  7165. def wait_signal(signal, timeout=10000):
  7166. """
  7167. Block loop until signal emitted, timeout (ms) elapses
  7168. or unhandled exception happens in a thread.
  7169. :param timeout: time after which the loop is exited
  7170. :param signal: Signal to wait for.
  7171. """
  7172. loop = QtCore.QEventLoop()
  7173. # Normal termination
  7174. signal.connect(loop.quit)
  7175. # Termination by exception in thread
  7176. self.thread_exception.connect(loop.quit)
  7177. status = {'timed_out': False}
  7178. def report_quit():
  7179. status['timed_out'] = True
  7180. loop.quit()
  7181. yield
  7182. # Temporarily change how exceptions are managed.
  7183. oeh = sys.excepthook
  7184. ex = []
  7185. def except_hook(type_, value, traceback_):
  7186. ex.append(value)
  7187. oeh(type_, value, traceback_)
  7188. sys.excepthook = except_hook
  7189. # Terminate on timeout
  7190. if timeout is not None:
  7191. QtCore.QTimer.singleShot(timeout, report_quit)
  7192. # # ## Block ## ##
  7193. loop.exec_()
  7194. # Restore exception management
  7195. sys.excepthook = oeh
  7196. if ex:
  7197. self.raiseTclError(str(ex[0]))
  7198. if status['timed_out']:
  7199. raise Exception('Timed out!')
  7200. def make_docs():
  7201. output = ''
  7202. import collections
  7203. od = collections.OrderedDict(sorted(commands.items()))
  7204. for cmd_, val in od.items():
  7205. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  7206. t = val['help']
  7207. usage_i = t.find('>')
  7208. if usage_i < 0:
  7209. expl = t
  7210. output += expl + '\n\n'
  7211. continue
  7212. expl = t[:usage_i - 1]
  7213. output += expl + '\n\n'
  7214. end_usage_i = t[usage_i:].find('\n')
  7215. if end_usage_i < 0:
  7216. end_usage_i = len(t[usage_i:])
  7217. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  7218. else:
  7219. extras = t[usage_i+end_usage_i+1:]
  7220. parts = [s.strip() for s in extras.split('\n')]
  7221. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  7222. for p in parts:
  7223. output += ' ' + p + '\n\n'
  7224. return output
  7225. '''
  7226. Howto implement TCL shell commands:
  7227. All parameters passed to command should be possible to set as None and test it afterwards.
  7228. This is because we need to see error caused in tcl,
  7229. if None value as default parameter is not allowed TCL will return empty error.
  7230. Use:
  7231. def mycommand(name=None,...):
  7232. Test it like this:
  7233. if name is None:
  7234. self.raise_tcl_error('Argument name is missing.')
  7235. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  7236. otherwise we will miss it and processing will silently continue.
  7237. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  7238. which is catched in exec_command and displayed in TCL shell console with red background.
  7239. Error in console is displayed with TCL trace.
  7240. This behavior works only within main thread,
  7241. errors with promissed tasks can be catched and detected only with log.
  7242. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  7243. TCL shell.
  7244. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  7245. '''
  7246. commands = {
  7247. 'help': {
  7248. 'fcn': shelp,
  7249. 'help': _("Shows list of commands.")
  7250. },
  7251. }
  7252. # Import/overwrite tcl commands as objects of TclCommand descendants
  7253. # This modifies the variable 'commands'.
  7254. tclCommands.register_all_commands(self, commands)
  7255. # Add commands to the tcl interpreter
  7256. for cmd in commands:
  7257. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  7258. # Make the tcl puts function return instead of print to stdout
  7259. self.tcl.eval('''
  7260. rename puts original_puts
  7261. proc puts {args} {
  7262. if {[llength $args] == 1} {
  7263. return "[lindex $args 0]"
  7264. } else {
  7265. eval original_puts $args
  7266. }
  7267. }
  7268. ''')
  7269. def setup_recent_items(self):
  7270. # TODO: Move this to constructor
  7271. icons = {
  7272. "gerber": "share/flatcam_icon16.png",
  7273. "excellon": "share/drill16.png",
  7274. 'geometry': "share/geometry16.png",
  7275. "cncjob": "share/cnc16.png",
  7276. "project": "share/project16.png",
  7277. "svg": "share/geometry16.png",
  7278. "dxf": "share/dxf16.png",
  7279. "pdf": "share/pdf32.png",
  7280. "image": "share/image16.png"
  7281. }
  7282. openers = {
  7283. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7284. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7285. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7286. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7287. 'project': self.open_project,
  7288. 'svg': self.import_svg,
  7289. 'dxf': self.import_dxf,
  7290. 'image': self.import_image,
  7291. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7292. }
  7293. # Open recent file for files
  7294. try:
  7295. f = open(self.data_path + '/recent.json')
  7296. except IOError:
  7297. App.log.error("Failed to load recent item list.")
  7298. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  7299. return
  7300. try:
  7301. self.recent = json.load(f)
  7302. except json.scanner.JSONDecodeError:
  7303. App.log.error("Failed to parse recent item list.")
  7304. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  7305. f.close()
  7306. return
  7307. f.close()
  7308. # Open recent file for projects
  7309. try:
  7310. fp = open(self.data_path + '/recent_projects.json')
  7311. except IOError:
  7312. App.log.error("Failed to load recent project item list.")
  7313. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent projects item list."))
  7314. return
  7315. try:
  7316. self.recent_projects = json.load(fp)
  7317. except json.scanner.JSONDecodeError:
  7318. App.log.error("Failed to parse recent project item list.")
  7319. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent project item list."))
  7320. fp.close()
  7321. return
  7322. fp.close()
  7323. # Closure needed to create callbacks in a loop.
  7324. # Otherwise late binding occurs.
  7325. def make_callback(func, fname):
  7326. def opener():
  7327. func(fname)
  7328. return opener
  7329. def reset_recent_files():
  7330. # Reset menu
  7331. self.ui.recent.clear()
  7332. self.recent = []
  7333. try:
  7334. f = open(self.data_path + '/recent.json', 'w')
  7335. except IOError:
  7336. App.log.error("Failed to open recent items file for writing.")
  7337. return
  7338. json.dump(self.recent, f)
  7339. def reset_recent_projects():
  7340. # Reset menu
  7341. self.ui.recent_projects.clear()
  7342. self.recent_projects = []
  7343. try:
  7344. fp = open(self.data_path + '/recent_projects.json', 'w')
  7345. except IOError:
  7346. App.log.error("Failed to open recent projects items file for writing.")
  7347. return
  7348. json.dump(self.recent, fp)
  7349. # Reset menu
  7350. self.ui.recent.clear()
  7351. self.ui.recent_projects.clear()
  7352. # Create menu items for projects
  7353. for recent in self.recent_projects:
  7354. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7355. if recent['kind'] == 'project':
  7356. try:
  7357. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7358. # Attach callback
  7359. o = make_callback(openers[recent["kind"]], recent['filename'])
  7360. action.triggered.connect(o)
  7361. self.ui.recent_projects.addAction(action)
  7362. except KeyError:
  7363. App.log.error("Unsupported file type: %s" % recent["kind"])
  7364. # Last action in Recent Files menu is one that Clear the content
  7365. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  7366. clear_action_proj.triggered.connect(reset_recent_projects)
  7367. self.ui.recent_projects.addSeparator()
  7368. self.ui.recent_projects.addAction(clear_action_proj)
  7369. # Create menu items for files
  7370. for recent in self.recent:
  7371. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7372. if recent['kind'] != 'project':
  7373. try:
  7374. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7375. # Attach callback
  7376. o = make_callback(openers[recent["kind"]], recent['filename'])
  7377. action.triggered.connect(o)
  7378. self.ui.recent.addAction(action)
  7379. except KeyError:
  7380. App.log.error("Unsupported file type: %s" % recent["kind"])
  7381. # Last action in Recent Files menu is one that Clear the content
  7382. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  7383. clear_action.triggered.connect(reset_recent_files)
  7384. self.ui.recent.addSeparator()
  7385. self.ui.recent.addAction(clear_action)
  7386. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7387. # self.ui.menufilerecent.set_submenu(recent_menu)
  7388. # recent_menu.show_all()
  7389. # self.ui.recent.show()
  7390. self.log.debug("Recent items list has been populated.")
  7391. def setup_component_editor(self):
  7392. # label = QtWidgets.QLabel("Choose an item from Project")
  7393. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7394. sel_title = QtWidgets.QTextEdit(
  7395. _('<b>Shortcut Key List</b>'))
  7396. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7397. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7398. settings = QSettings("Open Source", "FlatCAM")
  7399. if settings.contains("notebook_font_size"):
  7400. fsize = settings.value('notebook_font_size', type=int)
  7401. else:
  7402. fsize = 12
  7403. tsize = fsize + int(fsize / 2)
  7404. selected_text = _('''
  7405. <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  7406. <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7407. The normal flow when working in FlatCAM is the following:</span></p>
  7408. <ol>
  7409. <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  7410. <br />
  7411. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  7412. &nbsp;</li>
  7413. <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7414. <br />
  7415. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  7416. <br />
  7417. You can change the parameters in this screen and the flow direction is like this:<br />
  7418. <br />
  7419. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7420. </ol>
  7421. <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  7422. '''.format(fsize=fsize, tsize=tsize))
  7423. sel_title.setText(selected_text)
  7424. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7425. self.ui.selected_scroll_area.setWidget(sel_title)
  7426. def setup_obj_classes(self):
  7427. """
  7428. Sets up application specifics on the FlatCAMObj class.
  7429. :return: None
  7430. """
  7431. FlatCAMObj.app = self
  7432. ObjectCollection.app = self
  7433. Gerber.app = self
  7434. Excellon.app = self
  7435. Geometry.app = self
  7436. CNCjob.app = self
  7437. FCProcess.app = self
  7438. FCProcessContainer.app = self
  7439. def version_check(self):
  7440. """
  7441. Checks for the latest version of the program. Alerts the
  7442. user if theirs is outdated. This method is meant to be run
  7443. in a separate thread.
  7444. :return: None
  7445. """
  7446. self.log.debug("version_check()")
  7447. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7448. full_url = App.version_url + \
  7449. "?s=" + str(self.defaults['global_serial']) + \
  7450. "&v=" + str(self.version) + \
  7451. "&os=" + str(self.os) + \
  7452. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  7453. else:
  7454. # no_stats dict; just so it won't break things on website
  7455. no_ststs_dict = {}
  7456. no_ststs_dict["global_ststs"] = {}
  7457. full_url = App.version_url + \
  7458. "?s=" + str(self.defaults['global_serial']) + \
  7459. "&v=" + str(self.version) + \
  7460. "&os=" + str(self.os) + \
  7461. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7462. App.log.debug("Checking for updates @ %s" % full_url)
  7463. # ## Get the data
  7464. try:
  7465. f = urllib.request.urlopen(full_url)
  7466. except:
  7467. # App.log.warning("Failed checking for latest version. Could not connect.")
  7468. self.log.warning("Failed checking for latest version. Could not connect.")
  7469. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  7470. return
  7471. try:
  7472. data = json.load(f)
  7473. except Exception as e:
  7474. App.log.error("Could not parse information about latest version.")
  7475. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  7476. App.log.debug("json.load(): %s" % str(e))
  7477. f.close()
  7478. return
  7479. f.close()
  7480. # ## Latest version?
  7481. if self.version >= data["version"]:
  7482. App.log.debug("FlatCAM is up to date!")
  7483. self.inform.emit(_("[success] FlatCAM is up to date!"))
  7484. return
  7485. App.log.debug("Newer version available.")
  7486. self.message.emit(
  7487. _("Newer Version Available"),
  7488. _("There is a newer version of FlatCAM available for download:\n\n") +
  7489. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  7490. _("info")
  7491. )
  7492. def on_plotcanvas_setup(self, container=None):
  7493. """
  7494. This is doing the setup for the plot area (VisPy canvas)
  7495. :param container: widget where to install the canvas
  7496. :return: None
  7497. """
  7498. if container:
  7499. plot_container = container
  7500. else:
  7501. plot_container = self.ui.right_layout
  7502. self.plotcanvas = PlotCanvas(plot_container, self)
  7503. # So it can receive key presses
  7504. self.plotcanvas.native.setFocus()
  7505. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  7506. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  7507. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7508. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  7509. # Keys over plot enabled
  7510. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  7511. self.app_cursor = self.plotcanvas.new_cursor()
  7512. self.app_cursor.enabled = False
  7513. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7514. def on_zoom_fit(self, event):
  7515. """
  7516. Callback for zoom-out request. This can be either from the corresponding
  7517. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7518. with axes limits from the geometry bounds of all objects.
  7519. :param event: Ignored.
  7520. :return: None
  7521. """
  7522. self.plotcanvas.fit_view()
  7523. def on_zoom_in(self):
  7524. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7525. def on_zoom_out(self):
  7526. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7527. def disable_all_plots(self):
  7528. self.report_usage("disable_all_plots()")
  7529. self.disable_plots(self.collection.get_list())
  7530. self.inform.emit(_("[success] All plots disabled."))
  7531. def disable_other_plots(self):
  7532. self.report_usage("disable_other_plots()")
  7533. self.disable_plots(self.collection.get_non_selected())
  7534. self.inform.emit(_("[success] All non selected plots disabled."))
  7535. def enable_all_plots(self):
  7536. self.report_usage("enable_all_plots()")
  7537. self.enable_plots(self.collection.get_list())
  7538. self.inform.emit(_("[success] All plots enabled."))
  7539. def on_enable_sel_plots(self):
  7540. log.debug("App.on_enable_sel_plot()")
  7541. object_list = self.collection.get_selected()
  7542. self.enable_plots(objects=object_list)
  7543. self.inform.emit(_("[success] Selected plots enabled..."))
  7544. def on_disable_sel_plots(self):
  7545. log.debug("App.on_disable_sel_plot()")
  7546. # self.inform.emit(_("Disabling plots ..."))
  7547. object_list = self.collection.get_selected()
  7548. self.disable_plots(objects=object_list)
  7549. self.inform.emit(_("[success] Selected plots disabled..."))
  7550. def enable_plots(self, objects):
  7551. """
  7552. Disables plots
  7553. :param objects: list of Objects to be enabled
  7554. :return:
  7555. """
  7556. log.debug("Enabling plots ...")
  7557. self.inform.emit(_("Working ..."))
  7558. for obj in objects:
  7559. if obj.options['plot'] is False:
  7560. obj.options['plot'] = True
  7561. self.plots_updated.emit()
  7562. def disable_plots(self, objects):
  7563. """
  7564. Disables plots
  7565. :param objects: list of Objects to be disabled
  7566. :return:
  7567. """
  7568. # if no objects selected then do nothing
  7569. if not self.collection.get_selected():
  7570. return
  7571. log.debug("Disabling plots ...")
  7572. self.inform.emit(_("Working ..."))
  7573. for obj in objects:
  7574. if obj.options['plot'] is True:
  7575. obj.options['plot'] = False
  7576. self.plots_updated.emit()
  7577. def toggle_plots(self, objects):
  7578. """
  7579. Toggle plots visibility
  7580. :param objects: list of Objects for which to be toggled the visibility
  7581. :return:
  7582. """
  7583. # if no objects selected then do nothing
  7584. if not self.collection.get_selected():
  7585. return
  7586. log.debug("Toggling plots ...")
  7587. self.inform.emit(_("Working ..."))
  7588. for obj in objects:
  7589. if obj.options['plot'] is False:
  7590. obj.options['plot'] = True
  7591. else:
  7592. obj.options['plot'] = False
  7593. self.plots_updated.emit()
  7594. def clear_plots(self):
  7595. objects = self.collection.get_list()
  7596. for obj in objects:
  7597. obj.clear(obj == objects[-1])
  7598. # Clear pool to free memory
  7599. self.clear_pool()
  7600. def generate_cnc_job(self, objects):
  7601. self.report_usage("generate_cnc_job()")
  7602. # for obj in objects:
  7603. # obj.generatecncjob()
  7604. for obj in objects:
  7605. obj.on_generatecnc_button_click()
  7606. def save_project(self, filename, quit_action=False):
  7607. """
  7608. Saves the current project to the specified file.
  7609. :param filename: Name of the file in which to save.
  7610. :type filename: str
  7611. :param quit_action: if the project saving will be followed by an app quit; boolean
  7612. :return: None
  7613. """
  7614. self.log.debug("save_project()")
  7615. self.save_in_progress = True
  7616. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  7617. # Capture the latest changes
  7618. # Current object
  7619. try:
  7620. self.collection.get_active().read_form()
  7621. except:
  7622. self.log.debug("There was no active object")
  7623. pass
  7624. # Project options
  7625. self.options_read_form()
  7626. # Serialize the whole project
  7627. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  7628. "options": self.options,
  7629. "version": self.version}
  7630. if self.defaults["global_save_compressed"] is True:
  7631. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  7632. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  7633. # # Write
  7634. f.write(g)
  7635. self.inform.emit(_("[success] Project saved to: %s") % filename)
  7636. else:
  7637. # Open file
  7638. try:
  7639. f = open(filename, 'w')
  7640. except IOError:
  7641. App.log.error("Failed to open file for saving: %s", filename)
  7642. return
  7643. # Write
  7644. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  7645. f.close()
  7646. # verification of the saved project
  7647. # Open and parse
  7648. try:
  7649. saved_f = open(filename, 'r')
  7650. except IOError:
  7651. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  7652. return
  7653. try:
  7654. saved_d = json.load(saved_f, object_hook=dict2obj)
  7655. except:
  7656. self.inform.emit(
  7657. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  7658. f.close()
  7659. return
  7660. saved_f.close()
  7661. if 'version' in saved_d:
  7662. self.inform.emit(_("[success] Project saved to: %s") % filename)
  7663. else:
  7664. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  7665. settings = QSettings("Open Source", "FlatCAM")
  7666. lock_state = self.ui.lock_action.isChecked()
  7667. settings.setValue('toolbar_lock', lock_state)
  7668. # This will write the setting to the platform specific storage.
  7669. del settings
  7670. # if quit:
  7671. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  7672. # t.start()
  7673. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  7674. def start_delayed_quit(self, delay, filename, should_quit=None):
  7675. """
  7676. :param delay: period of checking if project file size is more than zero; in seconds
  7677. :param filename: the name of the project file to be checked periodically for size more than zero
  7678. :param should_quit: if the task finished will be followed by an app quit; boolean
  7679. :return:
  7680. """
  7681. to_quit = should_quit
  7682. self.save_timer = QtCore.QTimer()
  7683. self.save_timer.setInterval(delay)
  7684. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  7685. self.save_timer.start()
  7686. def check_project_file_size(self, filename, should_quit=None):
  7687. """
  7688. :param filename: the name of the project file to be checked periodically for size more than zero
  7689. :param should_quit: will quit the app if True; boolean
  7690. :return:
  7691. """
  7692. try:
  7693. if os.stat(filename).st_size > 0:
  7694. self.save_in_progress = False
  7695. self.save_timer.stop()
  7696. if should_quit:
  7697. self.app_quit.emit()
  7698. except Exception as e:
  7699. traceback.print_exc()
  7700. def on_options_app2project(self):
  7701. """
  7702. Callback for Options->Transfer Options->App=>Project. Copies options
  7703. from application defaults to project defaults.
  7704. :return: None
  7705. """
  7706. self.report_usage("on_options_app2project")
  7707. self.defaults_read_form()
  7708. self.options.update(self.defaults)
  7709. self.options_write_form()
  7710. def on_options_project2app(self):
  7711. """
  7712. Callback for Options->Transfer Options->Project=>App. Copies options
  7713. from project defaults to application defaults.
  7714. :return: None
  7715. """
  7716. self.report_usage("on_options_project2app")
  7717. self.options_read_form()
  7718. self.defaults.update(self.options)
  7719. self.defaults_write_form()
  7720. def on_options_project2object(self):
  7721. """
  7722. Callback for Options->Transfer Options->Project=>Object. Copies options
  7723. from project defaults to the currently selected object.
  7724. :return: None
  7725. """
  7726. self.report_usage("on_options_project2object")
  7727. self.options_read_form()
  7728. obj = self.collection.get_active()
  7729. if obj is None:
  7730. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7731. return
  7732. for option in self.options:
  7733. if option.find(obj.kind + "_") == 0:
  7734. oname = option[len(obj.kind) + 1:]
  7735. obj.options[oname] = self.options[option]
  7736. obj.to_form() # Update UI
  7737. def on_options_object2project(self):
  7738. """
  7739. Callback for Options->Transfer Options->Object=>Project. Copies options
  7740. from the currently selected object to project defaults.
  7741. :return: None
  7742. """
  7743. self.report_usage("on_options_object2project")
  7744. obj = self.collection.get_active()
  7745. if obj is None:
  7746. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7747. return
  7748. obj.read_form()
  7749. for option in obj.options:
  7750. if option in ['name']: # TODO: Handle this better...
  7751. continue
  7752. self.options[obj.kind + "_" + option] = obj.options[option]
  7753. self.options_write_form()
  7754. def on_options_object2app(self):
  7755. """
  7756. Callback for Options->Transfer Options->Object=>App. Copies options
  7757. from the currently selected object to application defaults.
  7758. :return: None
  7759. """
  7760. self.report_usage("on_options_object2app")
  7761. obj = self.collection.get_active()
  7762. if obj is None:
  7763. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7764. return
  7765. obj.read_form()
  7766. for option in obj.options:
  7767. if option in ['name']: # TODO: Handle this better...
  7768. continue
  7769. self.defaults[obj.kind + "_" + option] = obj.options[option]
  7770. self.defaults_write_form()
  7771. def on_options_app2object(self):
  7772. """
  7773. Callback for Options->Transfer Options->App=>Object. Copies options
  7774. from application defaults to the currently selected object.
  7775. :return: None
  7776. """
  7777. self.report_usage("on_options_app2object")
  7778. self.defaults_read_form()
  7779. obj = self.collection.get_active()
  7780. if obj is None:
  7781. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7782. return
  7783. for option in self.defaults:
  7784. if option.find(obj.kind + "_") == 0:
  7785. oname = option[len(obj.kind) + 1:]
  7786. obj.options[oname] = self.defaults[option]
  7787. obj.to_form() # Update UI
  7788. # end of file