FlatCAMApp.py 350 KB

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